[Fixed] Node.JS 18.16.1 -> Fetcherror: Unsafe Legacy Renegotiation – Node.js

by
Ali Hasan
jruby-openssl node-fetch node.js

Quick Fix: Quick Fix:

Implement the fix in the native Fetch API for Node 17+ using the undici module and crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT to allow insecure legacy renegotiation.

The Problem:

When making an API call using node-fetch library in Node.js, you encounter a ‘FetchError: Unsafe Legacy Renegotiation’ error when using Node.js version 18.16.1, while the code works without errors in Node.js version 16. The error is related to SSL renegotiation and affects HTTPS requests. You’re looking to understand why this error occurs only in Node.js version 18 and not in version 16, and if there are any potential drawbacks to using the suggested workaround.

The Solutions:

Solution 1: Use a custom agent

In Node.js 18, the default behavior for TLS connections is to disable legacy renegotiation. This can be overridden by using a custom agent, as shown below:

const crypto = require('crypto');
const { Agent } = require('undici');

fetch(url, {
  // @ts-ignore
  dispatcher: new Agent({
    connect: {
      rejectUnauthorized: false,
      secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT
    }
  })
});

Q&A

How can I fix the ‘Unsafe Legacy Renegotiation’ error in Node 18?

Use the ‘undici’ package and set ‘secureOptions’ to ‘SSL_OP_LEGACY_SERVER_CONNECT’.

Why the error is thrown by default in Node 18 but not in Node 16?

Node 18 has stricter security settings by default.

Are there any pitfalls to using the openssl.cnf from the suggested fix?

Unknown, but it’s recommended to use the ‘undici’ package instead.

Video Explanation:

The following video, titled "Related Video", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

This video provides further insights and detailed explanations related to the content discussed in the article.