Static Files in Next.js


When building a Next.js project you often might want to host some static files along side the application code. Next makes this easy with the public/ directory.

To host static files in Next.js you should place those files in a directory named public at the root of the application. Next will then know to host those files statically starting from the root path.

Hero image: island heads

Hosing static files with Next.js

Hosting static files is dead-easy in Next.js. You simply add the files you want to host at public/file and then it will be accessible at the route /file. It is possible for these static files to conflict in name with routes in the pages directory, so you'll have to be somewhat careful not to collide the names, but being able to host static files from the root path is useful for things like hosting a favicon or robots.txt which are expected to be at the webroot.

Generating static files at build time in Next.js

Now that Next.js supports some static site generation through getStaticProps you can actually write new static files at build time. Simply write some node.js code using the fs module to write new files into the public/ directory at build time and then you can reference them in your application. This is especially useful for things like pre-processing images.

Generally the flow will be:

For more info on the API around hosting static files you can check out the Next.js docs.

Note that if you use the assetPrefix configuration for Next it won't have any effect on how those assets are served. So you will have to prefix them yourself in the file path so that the CDN will know when to invalidate it's cache. Zeit's CDN does this automatically since it's aware of how Next.js projects are configured.