Nextjs public folder

Static file serving (e.g.: images)

create a folder called static in your project root directory. From your code you can then reference those files with /static/ URLs:

export default () => <img src="/static/my-image.png" alt="my image" />

Note: Don't name the static directory anything else. The name is required and is the only directory that Next.js uses for serving static assets.

for more read Docs


for Next.js 9: Next.js can serve static files, like images, under a folder called public in the root directory. Files inside public can then be referenced by your code starting from the base URL (/).

For example, if you add an image to public/my-image.png, the following code will access the image:

function MyImage() {
  return <img src="/my-image.png" alt="my image" />
}

export default MyImage

refrence: enter link description here


For web process anything in /public is at the url so easy. However, if you are trying to access the files on the server side of nextjs (either in one of the static async SSR, or as an API call) - as the paths there seem to need to be absolute paths. To access that you need to capture the running directory at build time, and then access it.

next.config.js:

module.exports = {
    serverRuntimeConfig: {
        PROJECT_ROOT: __dirname
    }
}

And a helper for getting server side paths:

import path from 'path'
import getConfig from 'next/config'

const serverPath = (staticFilePath: string) => {
  return path.join(getConfig().serverRuntimeConfig.PROJECT_ROOT, staticFilePath)
}

export default serverPath

Next.js has a public/ folder

Create stuff like public/favicon.png, public/robots.txt and that's all you need.

And put your static folder inside public to keep your assets in it with all assets bundling and compressing benefits.

/public
    /static
        /images
        /css
        /fonts
    robots.txt
    manifest.json

Documentation