69

Where is the public folder for a nextjs project?

I mean, is there somewhere where I can put favicon.png, google site verification, manifest.json, robots.txt, etc. ?

15 Answers 15

70

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

Sign up to request clarification or add additional context in comments.

5 Comments

It is important to note that the public directory should be in the root directory even if you are using the src directory.
I can't able to access my image :- <img src="/assets/images/my-image.png" alt="my image" /> how to access public folder inside folder image in next js ?
Note that for generated text files, you can use a Route Handler: app/rss.xml/route.ts where "rss.xml" is a folder name. For the end user, it will look like a file. For private files, you can also use a Route Handler, I've documented how to stream files from there: ericburel.tech/blog/nextjs-stream-files
In the latest version of Next.js using the App Router, the placement of favicon files and font directories has changed compared to previous versions. favicon file should be placed in the app directory, not in the public directory, For fonts, it's recommended to keep them in the app directory as well, Next.js provides a built-in next/font module that allows you to easily include and optimize fonts in your application.
Note that if you specify a basePath in your next.config.js, the asset will need to use that as a prefix. ex. public/img.png, with basePath:abc will be <img src="/abc/img.png" />
29

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

4 Comments

Hey, I tried your solution. On localhost, it throws this error when I start the server. Error: ENOENT: no such file or directory, open '/Roboto-Regular.ttf' On subsequent API calls, it works as expected and my font loads correctly. When I deploy to production then it crashes every time ENOENT: no such file or directory, open '/vercel/path0/public/Roboto-Regular.ttf Do you have any suggestion here?
@user3884753 - Hmm, looks like you are hosting on vercel, I'm not super familiar with how they work as a host personally. I'd double check the path, and maybe contact your server host support as that seems like an issue with pathing and the native os behavior (which they may be able to help with)
@user3884753 did you ever find a solution?
@Sliffcak Instead of serverRuntimeConfig, place PROJECT_ROOT inside env in the next config, and default it to empty string when using it in the code
24

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

Comments

11

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

1 Comment

As of May 1, 2019, public folder support has been added in addition to the static folder. See this PR github.com/zeit/next.js/pull/7213
8

The static directory has been deprecated in favor of the public directory. https://err.sh/zeit/next.js/static-dir-deprecated

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

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

2 Comments

This only works for me when running next dev. When I do next build and deploy, I get a 404
In my situation, when using the next build command, the public folder is not included. Therefore, if you plan on deploying the .next folder, make sure to also copy the public folder to the deployment machine/docker.
7

Next can use a /public folder. Just create one if you don't have it. I have my small project set up as:

project-root
    /public
        /blog-images
        /fonts
        favicon.ico
        etc.png
    /src
        /pages
        /components
        /styles
            globals.css
        /utils

Comments

3

You can create a public folder in the root of your project. NextJS would automatically grab the website's static content from the folder.

If an image is in public folder such that Image URL is: projectRoot/public/myImg.jpg then you can access it inside your JSX or TSX files by using /myImg.jpg

For more information check out the documentation: https://nextjs.org/docs/basic-features/static-file-serving

Comments

2

According to this issue you could serve static files server side, just like this (source):

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const { join } = require('path')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {
    const parsedUrl = parse(req.url, true)
    const rootStaticFiles = ['/robots.txt', '/sitemap.xml', '/favicon.ico']
    if (rootStaticFiles.indexOf(parsedUrl.pathname) > -1) {
      const path = join(__dirname, 'static', parsedUrl.pathname)
      app.serveStatic(req, res, path)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

Comments

2

the /public folder. You need to restart the website after adding files to this folder

Comments

1

You can place image inside public folder.

after that using import Head from "next/head" you can place <link rel="icon" type="image/png" href="relative path in public folder"/>

Comments

1

Where is the public folder for a nextjs project?

Answer: into the root directory of the project, you create public folder and put favicon.png into this.

You can reference the sample at https://github.com/dotuan9x/nextjs-boilerplate. I already use this for my website https://nghesachnoi.com and reality https://nghesachnoi.com/favicon.ico

Comments

0

I understand that you need to find the public folder, but if you want to put robots.txt, favicon, etc. you can add them in the app/ if you are using the nextjs app router.

Here are the docs.

All three things you mentioned(robots, favicon, manifest.json) are all placed in the app router and would work according to the docs and I have used this easily in my work projects as well!

Comments

0

You can put them in the root of app (When you use the App router structure):

If you use the Pages Router structure you can use the public folder Static Assets - Robots, Favicons, and others

Comments

0

In the root of your project, there's a public folder where you can add assets like favicon.png, robots.txt, and other static files. Any files placed here will be directly accessible from the root URL,

Nextjs Docs

Comments

0

If anyone like me here coming from react and trying to do this

import img from "img/image.jpg";

and facing the issue just import it directly in the img src tag like this

<img src="img/image.jpg" alt="img" />

assuming you have saved the image inside the public/img/ folder

and don't waste your time trying to figure out why is it not working even though the image is in the public folder and you are importing it like the other answer.

If you find out any alternative, let me know :)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.