Read static files in Netlify Functions API

Mustafa Ahmed
1 min readOct 28, 2021

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/

--

--