Setup Netlify serverless functions on local environment

Jan 24, 2025

I've ran into a lot of headaches trying to run the Netlify serverless functions locally. Probably because I was looking for an easy solution watching YouTube videos and asking Chat GPT, which were both outdated, rather than actually reading Netlify's quite comprehensive documentation or actually following what their CLI prompts suggested. I probably lost about 2 hours banging my head, trying to figure out why the functions were working properly on the Netlify servers, but I couldn't run them locally no matter what.

The solution was actually 2 lines of code. 2!

[functions]
  directory = "functions"

That's it.

So how would that work in a vite-react project?

Step 1. Install the Netlify CLI first.

npm install netlify-cli -g

Step 2. Create your project and install the dependencies.

npm create vite@latest react-netlify -- --template react
cd react-netlify
npm install
npm install axios

Step 3. Create a new file called netlify.toml in the root of your project. Create a new folder called functions and inside it a new folder called hello. In that new folder create a hello.mjs. Your project structure should look like this:

react-netlify/
├── functions/  
   ├── hello/  
      ├── hello.mjs  
├── src/  
├── netlify.toml   
├── index.html
etc..

Step 4. The magic lines of code. Inside netlify.toml add:

[functions]
  directory = "functions"

Step 5. Test

Create a new function for testing:

export async function handler(event, context) {
  const data = "Hello, World!"
  return {
    statusCode: 200,
    body: JSON.stringify({ message: data }),
  };
}

Call it in the react-app:

  const [helloWorld, setHelloWorld] = useState("");
  const callNetlifyFunction = async () => {
    try {
      const res = await axios.get("/.netlify/functions/hello");
      setHelloWorld(res.data.message);
    } catch (error) {
      console.error("Error calling Netlify function:", error);
      setHelloWorld("Error fetching data");
    }
  };

Render it:

  <button onClick={callNetlifyFunction}>Call Function</button>
  <h1>{helloWorld}</h1>

Step 6. Run the Netlify server.

netlify dev

"Hello, World!"

That's all folks.

gogov.dev