How to create a Static site public folder in Next.js?
Best practice with a public folder in nextjs
The Next.js provide inbuild static public folder support and serve all the statics site images, CSS, Google Site Verification, robots.txt, favicon.ico, etc., in the nextjs app.
You create a
public folder in the next.js root level. With the public folder, you access everything in production or built time.
Demo and play
You can play with code on codesandbox
What do you add to the public folder?
It depends upon you what you add to the public folder. for example, you add a favicon and fonts file in the public folder.
<link rel="stylesheet" href="/Inter-ExtraLight.ttf" /><link rel="stylesheet" href="/global.css" />
I recommended adding Favicon in the public folder. In my opinion, you can add fonts in the public and assets folder both working fine in nextjs.
How to access files in the public folder?
You can access the file used
/in the public folder. You do not need to import files into the public folder.
<Image src="/lake.png" alt="test public folder image" width="500" height="200" />
You do not add a CSS file in the public folder. Because nextjs use CSS module (style.module.css ) to add CSS for the component.
import "../public/style.module.css" // it not working
You can only add a global CSS file in nextjs.
<link rel="stylesheet" href="/global.css" />
You can also import the font files into CSS files.
- Create a public folder at the root level.
- You can add a verification HTML file inside the public folder.
- Do not use another name in
- You do not use
./like.pngto access the file.
- All the files you add to the public folder access after the built or production level.
- You do not need to import files in the public folder.
- Do not create a file with the same name in your public folder or the entire app.
In my experience, the public folder is only helpful for domain verification and other use based on requirements.
I hope my article solve your problem and give feed for improvement.
Feel free to like and share my article with others if you like my writing. You also tag on Twitter official_R_deep.