Error: Cannot find module ‘express’ – Netlify Functions

by

This issue happens when you’re using Netlify Functions and using a custom directory to store your functions.

Solution

Add this to your netlify.toml

[[plugins]]
  package = "@netlify/plugin-functions-install-core"

And add package.json to your custom directory

More information

In my case, this was my directory structure:

functions
└── src
|    | index.ts
| pnpm-lock.yaml
| package.json
| netlify.toml 
| verify.ts

And my netlify.toml looked like this:

[functions]
  external_node_modules = ["express"]
  node_bundler = "esbuild"
  directory = "src"
[[redirects]]
  force = true
  from = "/*"
  status = 200
  to = "/.netlify/functions/index/:splat"

This was copy paste from the Netlify article about running Express.js on Netlify Functions, except I’m redirecting people to / instead of /api like what was in the article. I also added a custom directory to simplify my file structure.

However, I found out that I was getting invocation errors and I tried to deploy from the Netlify CLI instead. I got a different error now about some dependency, and I kept on adding those to my package.json. But that took forever and I got bored.

I tried to add my package.json into my custom directory (src) instead but got another error about how I need to use a plugin or put the package.json in the top level or something. So I added the plugin, placed back the package.json and it still didn’t work

# netlify.toml
[functions]
  external_node_modules = ["express"]
  node_bundler = "esbuild"
  directory = "src"
[[redirects]]
  force = true
  from = "/*"
  status = 200
  to = "/.netlify/functions/index/:splat"
[[plugins]]
  package = "@netlify/plugin-functions-install-core"

I added the package.json and the pnpm-lock.yaml (for luck) into both the top level directory and my src folder, only then did it deploy properly.

functions
└── src
|    | index.ts
|    | package.json
|    | pnpm-lock.yaml
| pnpm-lock.yaml
| package.json
| netlify.toml 
| verify.ts

Hope this helps you out!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *