Skip to main content

HTTP Requests with Fetch API

The Fetch API is the modern way to send asynchronous HTTP requests in JavaScript. It provides a powerful and flexible feature set for making requests and handling responses.

Basic Fetch Request

Using async/await

The more modern and readable approach:

Aborting Fetch Requests

Aborting a fetch request in JavaScript is a common need. The signal option allows you to cancel requests at any time.

Using AbortController

To create a valid value for the signal option, you can use AbortController.signal after creating a new instance of AbortController. Then, you can use AbortController.abort() to cancel the request at any time.
This is particularly useful in scenarios where a request takes too long or the response is no longer needed, such as when a user navigates away from a page.

Timeout Pattern

Combine AbortController with a timeout:

Request Options

GET Request

POST Request

PUT Request

DELETE Request

Handling Responses

Check Response Status

Different Response Types

Error Handling

Comprehensive Error Handling

Advanced Patterns

Retry Logic

Caching Responses

Parallel Requests

Sequential Requests

Best Practices

Network requests can fail for many reasons. Always use try/catch or .catch() to handle errors gracefully.
The fetch API doesn’t reject on HTTP errors (like 404 or 500). Always check response.ok before processing the response.
In React components or when navigation occurs, use AbortController to cancel pending requests and prevent memory leaks.
Don’t let requests hang indefinitely. Implement timeout logic to improve user experience.
For frequently accessed data that doesn’t change often, implement caching to reduce network requests.