Skip to content

Instantly share code, notes, and snippets.

@kabilashgit
Last active July 25, 2023 07:29
Show Gist options
  • Save kabilashgit/1e57abd2c432c23a1ca04e8100490c83 to your computer and use it in GitHub Desktop.
Save kabilashgit/1e57abd2c432c23a1ca04e8100490c83 to your computer and use it in GitHub Desktop.
Solution: NextJs Public folder new items not accessible after build.

vercel/next.js#18005

Hi,

To anyone who is reading this thread looking for a solution to access files in the public folder at runtime but would prefer a simple solution that works with next you can do the following:

Create a new folder: "./pages/api/public" Add a new file to the folder: "[[...slug]].js" Add the following code to the file:

import fs from "fs"

export default function handler(req, res) {
		if (req.query.slug && req.query.slug.length) {
			const publicDir = __dirname.split(".next")[0] + "public/"
			const fileUrl = req.query.slug.join("/")
			fs.readFile(publicDir + fileUrl, (error, data) => {
				if(error) {
					return res.status(404).send(null)
				}
				return res.status(200).send(data)
			})
		} else {
			res.status(404).send(null)
		}
}

Now you can access the files in your public folder using "yourapplication:3000/api/public/*" Example:

You may need to slightly customize the code to your needs.

Hope this helps anyone in need! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment