How to Use Fetch in Node.js: Simple Guide with Examples
In Node.js (version 18 and above), you can use the built-in
fetch function to make HTTP requests just like in browsers. Simply call fetch(url) and handle the response with async/await to get data from APIs or websites.Syntax
The fetch function takes a URL string as the first argument and an optional options object as the second argument. It returns a Promise that resolves to a Response object.
- url: The web address you want to request.
- options: Optional settings like method (GET, POST), headers, and body.
- Response: The result object you can use to read data like JSON or text.
javascript
const response = await fetch(url, options); const data = await response.json();
Example
This example shows how to fetch JSON data from a public API and print a value from the response.
javascript
async function getUser() { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); if (!response.ok) { throw new Error('Network response was not ok'); } const user = await response.json(); console.log('User name:', user.name); } getUser().catch(console.error);
Output
User name: Leanne Graham
Common Pitfalls
- Not using
awaitor.then()to handle the asynchronousfetchcall. - Forgetting to check
response.okto handle HTTP errors. - Trying to use
fetchin Node.js versions before 18 without installing a package. - Not parsing the response body with
response.json()orresponse.text().
javascript
/* Wrong: Missing await and error check */ fetch('https://jsonplaceholder.typicode.com/users/1') .then(response => response.json()) .then(data => console.log(data.name)); /* Right: Using await and error check */ async function fetchUser() { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); if (!response.ok) { throw new Error('Failed to fetch'); } const data = await response.json(); console.log(data.name); } fetchUser();
Quick Reference
Remember these key points when using fetch in Node.js:
- Node.js 18+ has built-in
fetch, no extra install needed. - Use
awaitto wait for the response. - Check
response.okto catch errors. - Parse response with
response.json()orresponse.text(). - For older Node.js versions, use
node-fetchpackage.
Key Takeaways
Node.js 18+ includes a built-in fetch function similar to browsers.
Always use async/await and check response.ok to handle errors.
Parse the response body with response.json() or response.text() before use.
For Node.js versions before 18, install and import the node-fetch package.
Fetch is a simple way to make HTTP requests without extra libraries in modern Node.js.