How to Read Static Files in Netlify Functions API
whats the problem?
if you need to read a file (.txt, .json etc) from your public folder into your Netlify Functions API, the path resolution is not straightforward. your code might work locally using next dev, but when you deploy the build to Netlify, the paths don’t work anymore.
whats the fix?
first, you need to create a file netlify.toml in your root directory with the following code:
[functions]
included_files = ["public/*.txt"]
you can play around with directories or extensions using wildcard expressions (*)
second, your function needs the following code to read the file
import path from 'path';
export default async (req, res) => {
// ... ommitted
const filePath = path.resolve(`public/data.txt`);
fs.readFile(filePath, 'utf-8', (error, data) => {
console.log(data);
}));
// ... ommitted
}
that’s it, you should be able to read files from your public folder into your Netlify Functions API.
read more about configuring netlify.toml here: https://docs.netlify.com/configure-builds/file-based-configuration/