JavaScript logoJavaScript INTERMEDIATE

Fetch API

Modern JavaScript Fetch API for making HTTP requests

5 min read
fetchapihttpajaxjavascript

New to Async JavaScript? Start Here First!

This sheet covers the Fetch API for making HTTP requests. If you're new to promises, async/await, or asynchronous JavaScript patterns, we recommend starting with our async JavaScript fundamentals sheet first.

Start with Async JavaScript Fundamentals

Basic Requests

Common HTTP request patterns with Fetch API

GET Requests

Fetching data from APIs and handling responses

javascript
🟢 GET is the default method - no need to specify
💡 Use URLSearchParams for clean query string building
⚡ Set Accept header to specify expected response type
📌 Cache-Control headers can prevent stale data

POST Requests

Sending data to create new resources

javascript
🟢 Always set Content-Type for JSON, omit for FormData
⚡ FormData automatically sets multipart boundary
⚠️ Fetch doesn't support upload progress - use XMLHttpRequest
💡 Include request IDs for debugging and tracing

PUT, PATCH, DELETE

Updating and deleting resources with proper methods

javascript
📌 PUT replaces entire resource, PATCH updates fields
🟢 DELETE typically returns 204 No Content on success
💡 Create a reusable API client for consistent requests
⚡ Handle empty responses appropriately (204, 205)

Request Configuration

Advanced request options for headers, CORS, caching, and credentials

Headers & Authentication

Working with headers and authentication tokens

javascript
🔐 Store tokens securely, never in code or URLs
💡 Headers object provides better API than plain objects
⚡ Implement token refresh for seamless authentication
📌 Some headers are forbidden and cannot be set

CORS & Request Modes

Handling Cross-Origin Resource Sharing and request modes

javascript
⚠️ no-cors mode severely limits response access
🔐 credentials: include needed for cross-origin cookies
💡 Preflight requests happen with custom headers
📌 CORS errors appear as network failures in fetch

Cache Control

Managing request caching and cache strategies

javascript
⚡ force-cache improves performance for static resources
💡 no-cache still uses cache but validates first
📌 ETags enable efficient conditional requests
🟢 Service Workers provide powerful offline caching

Response Handling

Processing responses, handling errors, and parsing data

Response Types

Parsing different response formats and handling content types

javascript
🟢 Response body can only be read once - clone if needed
💡 Check content-type header to determine parsing method
⚡ Use streams for large files to avoid memory issues
📌 Always revoke object URLs to prevent memory leaks

Error Handling

Comprehensive error handling and retry strategies

javascript
❌ Fetch only rejects on network errors, not HTTP errors
⚡ Implement exponential backoff for retry delays
💡 Don't retry 4xx client errors, only 5xx server errors
🔴 Always set timeouts to prevent hanging requests

Advanced Features

Request cancellation, interceptors, and advanced patterns

Abort Controller

Cancelling requests and implementing timeouts

javascript
🔴 Always abort requests when component unmounts
⚡ Cancel duplicate requests to save bandwidth
💡 Use singleton pattern for search/autocomplete
📌 AbortController can't be reused after abort()

Request Interceptors

Creating middleware for requests and responses

javascript
💡 Interceptors enable centralized request/response handling
⚡ Add common headers, authentication, logging in one place
📌 Keep interceptor chain order in mind
🟢 Transform responses for consistent data access

File Operations

Uploading files and handling downloads with progress

javascript
📌 FormData automatically sets multipart/form-data header
⚠️ Fetch doesn't support upload progress - use XMLHttpRequest
💡 Chunk large files to avoid memory issues
⚡ Use Range headers for resumable downloads