Can't use 'require package' in custom function after updating to 1.20.0

Describe the problem/error/question

Hello,

After updating n8n to 1.20.0, I can’t use the “require” keyword in the code node to import third-party packages.

What is the error message (if any)?

When running this code:
const ip = require(‘ip’);
const IPCIDR = require(‘ip-cidr’);
I get the following error:
ERROR: Unknown error [line 2]

More info:

The error is similar to this:

I tried replacing ‘require’ with import like this:
const ip = require(‘ip’);
const IPCIDR = require(‘ip-cidr’);

By replacing them with:
import IPCIDR from ‘ip-cidr’;
import ip from ‘ip’;

But that leads to another error:
ERROR: ‘import’ and ‘export’ may only appear at the top level [line 1]
In the same page, someone mentioned that you have to add:

 { 
   "type": "module",
 }

to your package.json file, but I’m not sure which package.json to modify.

Example workflow

Error:

Previously working code (before 1.20.0):

const ip = require('ip');

inputData = ["10.11.12.13"];

const updatedData = [];

function isPrivate(ipAddress) {
  return ip.isPrivate(ipAddress);
}

for (const item of inputData) {
  const ipAddress = item;
  const isPrivateAddress = isPrivate(ipAddress);
  updatedData.push({ json: { data: isPrivateAddress } });
}

return updatedData;

Information on your n8n setup

  • n8n version:1.20.0
  • Database (default: SQLite):SQLite
  • n8n EXECUTIONS_PROCESS setting (default: own, main):default
  • Running n8n via (Docker, npm, n8n cloud, desktop app): Docker
  • Operating system: Ubuntu 22.04

Hi @CristianG, I don’t think this is an n8n problem. The code you have shared is still working in principle on n8n 1.20.0:

Can you confirm how exactly you are running your n8n instance? Which image do you use and which docker run command exactly are you using?

Hi @MutedJam,

Thanks for taking the time to investigate. You steered me in the right direction to solve it.

It appears this was not related to n8n, as you mentioned, but to a package I used to parse some IP addresses (ip-cidr). They released a new version 11 days ago (https://www.npmjs.com/package/ip-cidr/v/4.0.0?activeTab=versions), causing the problem I mentioned.
The solution was to keep using the older version (3.1.0) until they will fix it.

Thank you!
Cristian

Sweet, glad to hear you’ve figured it out and thank you for sharing your solution :slight_smile: