Angular 17 : ReferenceError: fetch is not defined

Angular 17 : ReferenceError: fetch is not defined

In this article you will solve the ReferenceError: Fetch Is Not Defined Error which is coming in Angular 17 with node version above 18. Let's get started

The Problem:

The problem which I face in Angular 17 is when I make the SSR (Server Side Rendering ) build of my project and deploy it to the cloud AWS (Amazon Web Services). The project is working fine and the routing is working fine when I route from the website with routerLink but When I paste a blog url in the search bar it shows me "Reference Error : Fetch Not defined". The error which is coming in the server files which are generated in the build. I was very confused about where I should fix this error. Because of this error the website index pages are de-indexing from the google search console as it is not crawling the page. Also I searched for this error on google and tried many solutions on the internet but none of the solutions works for me . After Spending so much time on this error I finally fixed the error.

The Solution:

The Angular 17 Build consists of 2 folders one is Browser which is a client side and other is server which is for server side. When the Angular page load it start from the server side and then load to client side so the build which is generating by the command "NG BUILD" having many server file in which some file are using fetch which is a browser api and the server file loaded in node js environment then i realize that i think the fetch is unavailable in the server side. What i do is go to the vscode and open the terminal and install a node-fetch package by this command "npm i node-fetch" and then open the server.ts file in the angular project. Add the below code in the server.ts file and then rebuild the project and boom the error is fixed.

 

import fetch from 'node-fetch'

(global as any).fetch = fetch;

 

This will create a fetch api for the server side and it will not cause any error. If you have any query feel free to contact.

 

Note : My node version is above 18 and Angular version is 17 (latest).

Leave a comment