everett1992
everett1992

Reputation: 2671

How to provide https agent or CA certificates to node's global fetch?

Node 18 has global fetch http client but because this a browser API it doesn't expose the http agent or tls options.

Node's fetch is implemented by undici, which has a Agent which can be passed as the dispatcher, but undici is not distributed with node.

import { Agent } from 'undici'
fetch(url, { dispatcher: new Agent(agentOptions) })

Is there any built in way to set tls options, like ca when using the built-in fetch?

Upvotes: 4

Views: 2631

Answers (2)

Ken Bellows
Ken Bellows

Reputation: 6942

Since this still comes up high in the google results for stuff around undici fetch with certificates, here's the solution (based on https://undici.nodejs.org/#/docs/best-practices/client-certificate, tweaked for fetch() instead of Client):

const { readFileSync } = require('node:fs')
const { Agent, fetch } = require('undici')

const agent = new Agent({
  connect: {
    ca: [
      readFileSync('/path/to/client-ca-crt.pem', 'utf-8')
    ],
    cert: readFileSync('/path/to/crt.pem', 'utf-8'),
    key: readFileSync('/path/to/key.pem', 'utf-8')
  }
})

const rest = await fetch('https://example.com/api/something', {
  // just examples, put whatever you'd normally put here
  method: 'GET',
  headers: {
    Accept: 'application/json'
  },

  // the important thing: include the agent
  agent
})

This is very similar to how node-fetch uses https.Agent instances. The only big difference in the API is that undici.Agent nests the TLS options within the connect property.

Upvotes: 0

Kai Roesner
Kai Roesner

Reputation: 605

You should be able to use the agent option to pass tls options, e.g.

const options = {
  host: '...',
  method: 'POST',
  cert: '...',
  key: '...'
}
const httpsAgent = new https.Agent(options)
const response = await fetch({ agent: httpsAgent })

Note that https.Agent appears to be underdocumented as stated here and does not mention the tls options.

I just found out about this today and haven't been able to try it out myself, yet. Will update here as soon as I've verified it.

Upvotes: -2

Related Questions