Search code examples
node.jsfetch-api

how can i use native fetch with node in typescript (node v17.6)


In the console, when running node --experimental-fetch the fetch command is now natively enabled (node version >=17.6). see below

native fetch with node

However, when I add a typescript layer, I always get error TS2304: Cannot find name 'fetch'.

how can I solve this?

background idea: use fetch natively and get rid of node-fetch and @types/node-fetch dependencies

tsconfig.json and general setup: https://github.com/nexys-system/server-boilerplate/blob/master/tsconfig.json

see also:


Solution

  • There are only 2 easy/lazy solutions at the moment (check Ruben's answer for a proper one):

    1. You can set "lib": ["dom"] in your tsconfig.json
    2. You can add /// <reference lib="dom" /> at the top of the files in which you use fetch

    I personally prefer #2 as I can more easily keep track of where I am using this hack.

    Beware that "this tells TypeScript that you intend to run this code in a browser environment, allowing you to use DOM-specific globals. This makes type checking more lax and can lead to unexpected runtime errors".