SonickSeven
SonickSeven

Reputation: 584

How to access files uploaded to the public folder in Next.js?

I have a project in Next.js. I have that upload files and share that in public URL to this project.

With npm run dev first I uploaded files to public folder and it worked fine, but when I change to npm run start and upload files, the files upload to public folder but with URL http://mydomain/fileuploaded.jpg it did not show, is rare but it's there.

I searched on the Internet but I didn't find a solution for this problem.

Upvotes: 8

Views: 13997

Answers (3)

Johnny Missile
Johnny Missile

Reputation: 292

a bit late but if someone need the same.

If your goal is to upload and get picture from your next server, you can instead of using the Next router, getting the image by yourself by create a route /api/images/[id] where [id] is your file name and you manually with fs send the picture back.

something like:

const file = await fs.readFile(`./uploads/image.png`)

res.setHeader('Content-Type', 'image/png')
res.send(file)

Upvotes: 1

bas080
bas080

Reputation: 469

Try and use nginx or another webserver to serve the public directory. That way it will serve newly added files without having to write extra code to serve files in nextjs.

server {
  /images/ {
    root /var/www/site/public
  }
}

Upvotes: 4

juliomalves
juliomalves

Reputation: 50278

From Next.js documentation:

Only assets that are in the public directory at build time will be served by Next.js. Files added at runtime won't be available.

You'll have to persist the uploaded files somewhere else if you want to have access to them in the app at run time.


Alternatively, you could setup your own custom server in Next.js, which would give you more control to serve static files/assets.

You can also achieve something similar using API routes instead. See Next.js serving static files that are not included in the build or source code for details.

Upvotes: 14

Related Questions