Skip to content
New: a free website for your business, live in 48 to 72 hoursWorkflow automation on n8n and Claude, built for your businessFixed price, agreed before we start · Live in 5 to 10 business days30-day money-back guarantee on every planProfessional firms · Agencies · E-commerceYou own every workflow, in your own n8nClaude API: your data is not used for trainingHuman approval on every sensitive stepFree automation audit, no obligation
PURIST
30 days
Money-back window
14 h/wk
Modeled time saved
99.97%
Uptime SLA
< 7 days
Deploy time
PURIST AI
Claude Opus 4.7 · n8n v1.71 · <80ms
What type of business are you running? I'll show you exactly which processes we'd automate first and your estimated ROI.
Powered by n8n + Claude Opus 4.7 Get my free automation plan →
Fix "Cannot find module" in the n8n Code Node (npm Packages, Docker, Cloud)
Guides 7 min read · 1,607 words

Fix "Cannot find module" in the n8n Code Node (npm Packages, Docker, Cloud)

"Cannot find module" in the n8n Code node has three causes: the module is not allowed, not installed, or you are on n8n Cloud. Here is the exact fix for each, including Docker and task runners.

Steve, founder of PURIST

November 6, 2026

PURIST: Stuck on n8n? Our n8n experts fix and build workflows like this one, at a fixed price →

You write const _ = require('lodash') in a Code node, run it, and get "Cannot find module 'lodash'". Or you write import axios from 'axios' and get "'import' and 'export' may only appear at the top level". Both errors are by design: the Code node runs in a sandbox that blocks modules until you explicitly allow them. Here is how to fix it on each type of installation.

In short. On self-hosted n8n you must do two things: install the package where n8n runs (for Docker, build a custom image), and allow it with NODE_FUNCTION_ALLOW_EXTERNAL (npm packages) or NODE_FUNCTION_ALLOW_BUILTIN (Node.js modules like crypto or fs). If you use task runners in external mode, set these on the runner, not on the main n8n container. On n8n Cloud you cannot add packages: only crypto and moment are available.

Fix "Cannot find module" in the n8n Code Node (npm Packages, Docker, Cloud): workflow diagram
A module must be installed in the image that runs the code and allowed by environment variable. Illustration: PURIST.

First: replace import with require

The n8n sandbox does not support import and export. The official fix is to switch to require:

javascript
// Not supported in the Code node:
// import axios from 'axios';
// Use this instead:
const axios = require('axios');

If you still get "Cannot find module" after this change, continue below.

Cause 1: the module is not allowed

For security reasons, the Code node blocks imports by default, including Node.js built-in modules. Two environment variables lift the restriction:

VariableAllowsExample
NODE_FUNCTION_ALLOW_BUILTINNode.js built-in modulescrypto,fs or * for all
NODE_FUNCTION_ALLOW_EXTERNALnpm packages from n8n's node_modules foldermoment,lodash
bash
# Allow only crypto
export NODE_FUNCTION_ALLOW_BUILTIN=crypto
# Allow every built-in module
export NODE_FUNCTION_ALLOW_BUILTIN=*
# Allow two npm packages
export NODE_FUNCTION_ALLOW_EXTERNAL=moment,lodash

Restart n8n after changing them. Allow only what you need: * on built-ins also allows fs and child_process, which lets any workflow editor read files or run commands on the server.

Fix "Cannot find module" in the n8n Code Node (npm Packages, Docker, Cloud): node settings
The two variables the sandbox checks, and require() instead of import. Illustration: PURIST.

Cause 2: the package is not installed where n8n runs

Allowing a package does not install it. NODE_FUNCTION_ALLOW_EXTERNAL only allows modules that already exist in n8n's node_modules folder.

n8n installed with npm

Install the package in the same environment as n8n, then restart:

bash
npm install -g lodash

The exact folder depends on how you installed n8n. The rule is that the package must be resolvable from where n8n runs.

n8n in Docker

Installing a package inside a running container is lost at the next update. The documented approach is to extend the official image:

dockerfile
FROM n8nio/n8n:latest
USER root
RUN npm install -g lodash
USER node

Build it, point your docker-compose.yml at the new image, and add the variables:

yaml
services:
  n8n:
    build: .
    environment:
      - NODE_FUNCTION_ALLOW_EXTERNAL=lodash
      - NODE_FUNCTION_ALLOW_BUILTIN=crypto

Pin the base image to the version you run in production rather than latest, so a rebuild does not upgrade n8n by surprise.

Cause 3: task runners in external mode

Recent n8n versions execute Code node scripts in task runners. The documentation is explicit: if your instance uses task runners in external mode, set NODE_FUNCTION_ALLOW_BUILTIN and NODE_FUNCTION_ALLOW_EXTERNAL on the task runners (in the runners configuration), not on the main n8n container. The package must also be installed in the runner image, which is n8nio/runners for the official setup.

This is the most common reason a configuration that worked before an upgrade stops working: the variables are still on the main container, but the code now runs elsewhere.

Cause 4: you are on n8n Cloud

n8n Cloud does not support importing external npm modules. Two modules are available there: crypto and moment. If you need another library on Cloud, you have three options:

  • Rewrite the logic in plain JavaScript. Most uses of lodash have a one-line native equivalent.
  • Use a dedicated n8n node: Crypto, Date & Time, HTML, XML, Compression and Convert to File cover many needs.
  • Call an external endpoint (a small serverless function) with the HTTP Request node.

Quick checklist

  1. 1 import replaced with require.
  2. 2 Package installed in the image or environment that executes the code (main container or runner).
  3. 3 Package name listed in NODE_FUNCTION_ALLOW_EXTERNAL, or built-in module in NODE_FUNCTION_ALLOW_BUILTIN.
  4. 4 Variables set on the task runner if you use external mode.
  5. 5 n8n restarted.
  6. 6 Not on n8n Cloud, where only crypto and moment exist.

Worked example: a custom image with two packages

You want lodash and date-fns in Code nodes on a Docker Compose install. Here is the full setup.

Dockerfile (next to your compose file):

dockerfile
FROM n8nio/n8n:1.112.0
USER root
RUN npm install -g lodash date-fns
USER node

Replace the version tag with the exact version you run today. Pinning means a rebuild never upgrades n8n by surprise.

docker-compose.yml:

yaml
services:
  n8n:
    build: .
    restart: unless-stopped
    environment:
      - NODE_FUNCTION_ALLOW_EXTERNAL=lodash,date-fns
      - NODE_FUNCTION_ALLOW_BUILTIN=crypto
    volumes:
      - n8n_data:/home/node/.n8n
volumes:
  n8n_data:

Then rebuild and restart:

bash
docker compose build
docker compose up -d

Test node (Code, All Items):

javascript
const _ = require('lodash');
const { formatDistanceToNow } = require('date-fns');
return [{ json: {
  lodash: typeof _.chunk === 'function',
  dateFns: formatDistanceToNow(new Date(Date.now() - 3600000)),
} }];

If both values come back, the setup works. Keep this test workflow and run it after every upgrade.

If your instance uses external task runners

In external mode, Code node scripts run in a separate runner container, not in the main n8n container. Two consequences:

  • the package must be installed in the runner image (the official one is n8nio/runners), by extending it the same way;
  • NODE_FUNCTION_ALLOW_BUILTIN and NODE_FUNCTION_ALLOW_EXTERNAL must be set in the runner configuration, as the n8n documentation states.

A quick way to tell which setup you have: look for a runners service in your compose file, or for N8N_RUNNERS_MODE=external in the environment.

Troubleshooting table

SymptomLikely causeFix
"Cannot find module 'x'" right after adding itPackage not in the image that executes codeInstall it in that image (main or runner) and rebuild
Works on one server, not the otherDifferent env vars or imagesCompare docker inspect environment and image tags
Broke after an n8n upgradeRebuilt from a new base without the package, or code moved to runnersRebuild the custom image; move variables to the runner
"'import' and 'export' may only appear at the top level"ES module syntaxUse require()
require('fs') failsBuilt-in not allowedAdd fs to NODE_FUNCTION_ALLOW_BUILTIN, if you accept the risk
Anything on n8n CloudCloud does not allow external modulesUse built-in nodes, plain JavaScript, crypto or moment

Native JavaScript replaces most utility packages

Before adding a dependency, check whether plain JavaScript already does the job. It keeps workflows portable to n8n Cloud and to the next server.

lodash habitPlain JavaScript
_.uniqBy(list, 'email')[...new Map(list.map((x) => [x.email, x])).values()]
_.groupBy(list, 'status')Object.groupBy(list, (x) => x.status) (recent Node.js) or a reduce
_.chunk(list, 50)A for loop with slice(i, i + 50)
_.get(obj, 'a.b.c')obj?.a?.b?.c
_.pick(obj, ['a', 'b'])({ a: obj.a, b: obj.b })

Common mistakes to avoid

  • npm install inside a running container. It works until the next restart or update, then everything breaks at night.
  • **Allowing * to make an error go away.** It also opens child_process to every workflow editor.
  • Forgetting the restart. Environment variables are read at startup.

Production checklist

  • Only the modules you need allowed, never * on a shared instance.
  • Packages baked into a pinned custom image, not installed by hand in a running container.
  • Variables set where the code runs (main container or task runner).
  • A test workflow that requires each allowed module after every n8n upgrade.

Frequently asked questions

Can I install npm packages on n8n Cloud?

No. n8n Cloud does not allow external npm modules in the Code node. The crypto module and the moment package are available.

Where do I put NODE_FUNCTION_ALLOW_EXTERNAL with task runners?

On the task runners, not on the main n8n instance, when runners run in external mode. The package must also exist in the runner image.

Is NODE_FUNCTION_ALLOW_BUILTIN=* safe?

It allows every Node.js module, including fs and child_process. Anyone who can edit a workflow could then read server files or run commands. List only the modules you need.

Why does require work in one n8n instance and not another?

The variables or the installed packages differ between the two. Compare the environment variables of the container or runner that executes the code, and check that the package exists in that image.

How do I check which modules my n8n allows?

Look at the NODE_FUNCTION_ALLOW_BUILTIN and NODE_FUNCTION_ALLOW_EXTERNAL values in the environment of the container that runs your code, for example with docker inspect.

Do community nodes need NODE_FUNCTION_ALLOW_EXTERNAL?

No. Community nodes are installed and loaded differently. These variables only govern require() inside Code nodes.

Can I use axios in the n8n Code node?

On self-hosted n8n, if it is installed and allowed. In most cases the HTTP Request node is the better choice because it manages credentials, retries and pagination.

Tags

n8ncode nodenpmdockerself-hostederror
Steve, founder of PURIST

Steve founded PURIST, a workflow automation studio working with n8n, Make and Claude AI, and is the point of contact on every project. Prices and features in our articles come from vendor documentation and public pricing pages. How we research and score tools.

Complete guide

Automation Tools & Platforms

11 min read n8n Code Node: 15 JavaScript Examples You Can Copy and … 8 min read n8n Code Node With Multiple Inputs: 3 Methods That Work 7 min read n8n Code Node Errors Fixed: "Code doesn't return items … 7 min read $env and Credentials in the n8n Code Node: What Works a… 7 min read n8n Code Node Binary Data: Read, Change and Return File… 7 min read Python in the n8n Code Node (n8n 2.x): Setup, Syntax an… 7 min read Fix n8n "The requested webhook is not registered" (Test… 6 min read n8n Webhook URL: Test vs Production, and How to Change … 7 min read n8n Respond to Webhook: Return JSON, Status Codes, Redi… 8 min read Secure an n8n Webhook: Header Auth, Basic Auth, JWT and… 7 min read n8n Webhook Not Working? 10 Causes and How to Fix Each … 7 min read n8n HTTP Request Pagination: Every Pattern With Working… 7 min read n8n HTTP Request Authentication: API Keys, Bearer Token… 7 min read n8n HTTP Request Timeout and "Aborted" Errors: Causes a… 7 min read Upload and Download Files With the n8n HTTP Request Nod… 6 min read Fix ECONNREFUSED in n8n: Docker, localhost and 127.0.0.… 6 min read n8n 429 Too Many Requests: Batching, Retries and Rate L… 6 min read Fix redirect_uri_mismatch for n8n OAuth2 Credentials (G… 7 min read n8n Expression Errors Fixed: "Referenced node is unexec… 6 min read Anatomy Claude skill: what it is, how to install it, an… 5 min read How to explain a business process with the Anatomy skil… 5 min read Anatomy vs Mermaid vs Excalidraw: which to explain a wo… 14 min read n8n LinkedIn Job Automation: Auto-Apply, Track, and Fol… 16 min read n8n HTTP Request Node: Complete Documentation and Examp… 18 min read The future of automation: how our engineering team is s… 8 min read n8n vs Make vs Zapier: the honest comparison your busin… 11 min read n8n vs Make vs Zapier: an honest comparison for product… 7 min read Webhook vs polling: the architecture decision that dete… 24 min read n8n tutorial: build your first production workflow in u… 26 min read The 9 best Zapier alternatives in 2026: an honest ranki… 21 min read Make.com tutorial: build powerful automations without c… 19 min read Automation consultant vs DIY: how to decide what is rig… 14 min read n8n Self-Hosted vs Cloud: The Complete Decision Guide (… 15 min read 5 Zapier Free Alternatives That Handle Real Production … 15 min read WhatsApp Business Automation With n8n: Build a 24/7 Cus… 17 min read Google Workspace Automation: 15 Workflows for Sheets, D… 16 min read Claude AI for Business Automation: What It Does, What I… 15 min read Airtable Automation With n8n: 10 Workflows That Make Yo… 15 min read Droven.io AI Automation Tools: Full Review and Best Alt… 14 min read Droven.io RPA and Business Automation: An Honest 2026 R… 15 min read Enterprise Workflow Automation: The Complete Guide for … 13 min read Document Workflow Automation: Software, Implementation,… 14 min read Marketing Automation Workflow: From Content Creation to… 16 min read Ad Campaign Workflow Data Model and SDR Inbound Pipelin… 14 min read ComfyUI Workflows for Business: Product Photography, Ma… 13 min read GPT-5.2 for Business Workflows and the spec-workflow-mc… 17 min read ServiceNow vs IBM BAW vs n8n: Enterprise Workflow Autom… 16 min read 9 Best Workflow Automation Tools for Small Business in …

Keep reading

More from the blog.

All articles

From audit to deployment

Experience the automation
these articles are about.

Get my free automation plan →