Next.js Discord

Discord Forum

Issue- Nextjs 13 use server return response to client side

Answered
bscdev#1145 posted this in #help-forum
Open in Discord
I could not able to return server response to client side

image is uploaded to aws s3 and returned data fron s3 is an object. When I an console log this returned data from s3 at server side then i can see values of this uploaded data object.

Only the issue is when ever I return this data to client side as "uploadedImage", l get empty an object at client side.

Could any one help me and tell me how to pass this data from server side to client side.

"use server"

export sync function uploadService({image}){

   ................
   .....................
   S3.upload(options, (err, data)=>{
  if(err)({
  throw New Error(err)
  }
return {uploadedImage: data}
});
}


"use client"

async function handleUpload(){

  const  uploadedImage   =  await              uploadService({image: url})

 console.log(uploadedImage)

}
Answered by bscdev#1145
Hello Everyone, issue has resolved. I used server actions to implement upload method and s3 side used cdn to read s3 url. In server actions method I used promise and resolve technique to make the s3 upload function async. Also I used aws-sdk version 3 since version 2 is not suitable to Nextjs14. Thanks. However aws-sdk version 2 is more efficient than version3 according to my experience but if you want to send uploaded image back to client side then version 2 can not be used.
View full answer

69 Replies

Can you format your code using triple backticks like this?

```js
paste code here
```
I just formated my code.
Indentation Done.
can you fix the indentation and the typo
@/* @__PURE__ */ alfonsus even there is no indentation, you can still provide resolution if you can.
indentation and syntax highlighting help people to pick out the error just by checking the code. for most errors here, we can usually find out the error without even testing it locally. but indentation and syntax highlighting are critically important for us to be able to do that. no one here is required to help you, so to gain the chance of getting assistance, [help us help you](https://nextjs-faq.com/good-question).
Ok i will do it.Apologise.
I would if i can, i copy pasted the code to VSCode and it cannot even fix the indentation so i really cant help you
ok doing that
like
thanks for omitting the uneccesary part but theres typos too
could not able to return server response to client side

image is uploaded to aws s3 and returned data fron s3 is an object. When I an console log this returned data from s3 at server side then i can see values of this uploaded data object.

Only the issue is when ever I return this data to client side as "uploadedImage", l get empty an object at client side.

Could any one help me and tell me how to pass this data from server side to client side.

"use server"

export async function uploadService({image}){
    try {
        if (!image){
            throw new Error(err)
          }
    
            .......................................
               s3 bucket param options are here
            ......................................   

         
      S3.upload(options, async(err, data) => {
        if (err) {
          console.log(err);
          throw new Error(err)
        }
        return {uploadedImage: data};
     
        });

    } catch (error) {
        throw new Error(`Something went wrong please try again:${error.message}`); 
   
}


"use client"

async function handleUpload(){
   const  uploadedImage = await uploadService({image: url})
   console.log(uploadedImage)

}
try
let res
S3.upload(options, async(err, data) => {
  if (err) {
    console.log(err);
    throw new Error(err)
  }
  res = {uploadedImage: data};
});
return res
@/* @__PURE__ */ alfonsus I tried that way. but in client side it says undefined data.
@bscdev#1145 <@194128415954173952> I tried that way. but in client side it says undefined data.
try return "Something" and see if it returns the string to the client
@/* @__PURE__ */ alfonsus I tried sending return "Something" to client and image got uploaded to s3 too. and I reveive something as string in clientside. only getting issue in sending objects. because after image is uploaded to s3 gives uploaded data as an object. I need to send this object to clientside.
because server action cant return Class because it has to be parsed to JSON
as with anything, you can't return class from server to client
s3 provides data = {
ETag: '"9753Dsfghyu5f257050bbbbbbe064f0"',
ServerSideEncryption: 'AES256',
Location: 'https://myblog.s3.amazonaws.com/oU87oSjlYGVHyOudQnJ2l.jpeg',
key: 'oU87oSjlYGVHyOudQnJ2l.jpeg',
Key: 'oU87oSjlYGVHyOudQnJ2l.jpeg',
Bucket: 'myblog'
}
what happen if you console.log(JSON.stringify(data)) (data from S3.upload)
let me check
it gives data = {
"ETag": '"9753Dsfghyu5f257050bbbbbbe064f0"',
" ServerSideEncryption": 'AES256',
"Location": "https://myblog.s3.amazonaws.com/oU87oSjlYGVHyOudQnJ2l.jpeg",
"key": "oU87oSjlYGVHyOudQnJ2l.jpeg",
"Key": "oU87oSjlYGVHyOudQnJ2l.jpeg",
"Bucket": "myblog"
}
i did res = {uploadedImage: JSON.stringify(data)}; and return res . Still its undefined at client.
I tested this to the api route too app/api/upload-service -> there I found another error while I am sending the data via NextResponse. Error was : " headers undefined".
                                                                                                                                                                                                                                                                   return NextResponse.json(
            {
               uploadedImage: data,
            },
            { status: 200 }
            );
Sure I am posing the new code
this is only happeing sending image objects from server to client side. If I am sending json data to client side it works fine.
Peterbald
Hi Please try to make the api for uploading and call uploading server function in the API.
And try to return response from uploading to Client as a response.json data...
I think he wants to do it with Server Actions
New Code: -

"use server"

export async function uploadService({image}){
    try {
        if (!image){
            throw new Error(err)
          }
    
            .......................................
               s3 bucket param options are here
            ......................................   

       let res;   
      S3.upload(options, async(err, data) => {
        if (err) {
          console.log(err);
          throw new Error(err)
        }
           console.log(JSON.stringify(data));
         res = {uploadedImage: JSON.stringify(data)};
     
        });
         return res
    } catch (error) {
        throw new Error(`Something went wrong please try again:${error.message}`); 
   
}


"use client"

async function handleUpload(){
   const  uploadedImage = await uploadService({image: url})
   console.log(uploadedImage)

}
Now I am doing it with server actions only. The problem I am facing in server actions.
doesn't it need to be awaited first?
await S3.upload
and res = { data } (no need JSON.stringify)
can you give link to the documentation of S3.upload? or just give the name of the library
@Peterbald Hi Please try to make the api for uploading and call uploading server function in the API. And try to return response from uploading to Client as a response.json data...
@Peterbald I tried that. I am getting headers error when I am sending image objects. I am using Nextjs 13.4.10 . I passed headers too as content type image/* in NextResponse but error persists.
I tried await S3.upload but it throws error and as per AWS docs S3.upload function to be async like this S3.upload(options, async(err, data) => { }
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html
                                                                                                                                                                                                                                                            s3.upload (uploadParams, function (err, data) {
     if (err) {
        console.log("Error", err);
      } if (data) {
        console.log("Upload Success", data.Location);
       }
}); 
well
remove this async then
i dont think you need it no?
I used same s3 method in nextjs pagerouter just sent data to client by just res.send(data). it works in page router.
ok let me remove async and check again
let res = "Empty";   
S3.upload(options, (err, data) => {
if (err) {
console.log(err);
throw new Error(err)
}
console.log(JSON.stringify(data));
res = {uploadedImage: JSON.stringify(data)};
});
return res
try like this
I did exactly as above and tested. In client side I am getting "Empty". Image is uploaded to s3.
import { NextApiRequest, NextApiResponse } from 'next';
import multer from 'multer';
import { getTextExtractor } from 'office-text-extractor';

interface NextApiRequestWithFiles extends NextApiRequest {
files: Express.Multer.File[];
}

const upload = multer({ storage: multer.memoryStorage() });

export const config = {
api: {
bodyParser: false,
},
};

export default async (req: NextApiRequestWithFiles, res: NextApiResponse) => {
console.log("parse-here");
await new Promise((resolve, reject) => {
upload.array('files')(req as any, res as any, (err) => {
if (err) {
return reject(err);
}
resolve(null);
});
});

const files = req.files as Express.Multer.File[];
const results: string[] = [];

for (const file of files) {
const content = await handleFileContent(file.buffer, file.mimetype, file.originalname);
results.push(content);
}

res.json({ files: results });
};
This is the my uploading API function
@Peterbald Multer is a middleware which will assist in uploading files in s3 . It has no role in returning data to client side. My issue is in sending image objects to client side. The code you sent is for page router. Even my code is working fine in page router just sending data res.send(data) to client.
i would suggest you init a new project with latest version of next and see if it works because I had some issue with external package in server action with <= 14.0.3
@Ray initally I was created the project with latest version only. but lots of bugs were coming out. So I degraded to a stable version i.e 13.4.10.
However I will try that too. Thanks all for your assistance. I will let you know once I resolve this issue.Thanks to All @/* @__PURE__ */ alfonsus @Peterbald @Ray
13.4.10
that was before server action was stable 💀
it was declared as stable in 14.0.0
ok then I will upgrade and check
But with 13.4.10 also it works fine I do not return any image objects to client from server. other json objects(other than image) and datas can be easily pass to client side.
yes it can return value but if I use external package in server action it wasn't working for me in earlier version
which use async await
ok
Hello Everyone, issue has resolved. I used server actions to implement upload method and s3 side used cdn to read s3 url. In server actions method I used promise and resolve technique to make the s3 upload function async. Also I used aws-sdk version 3 since version 2 is not suitable to Nextjs14. Thanks. However aws-sdk version 2 is more efficient than version3 according to my experience but if you want to send uploaded image back to client side then version 2 can not be used.
Answer
Yes , latest version of aws-sdk to be used with Nextjs serveractions otherwise it is difficult to return the bucket details back to client . bucket details are very important if you want to delete the image instantly even before it saves to the DB. The main issue in my case was -> aws-sdk@ previous version was not run asynchronusly due to that upload method executes an empty return back to client before s3 upload finishes. Latest version resolves this issue since it uses async/await.