JAVASCRIPT
Authenticating JavaScript `fetch` Requests with JWT
Secure your client-side JavaScript API calls by learning how to include JSON Web Tokens (JWT) in the Authorization header for protected endpoints using `fetch`.
/**
* Fetches data from a protected API endpoint using a JWT for authentication.
* @param {string} url The API endpoint URL.
* @param {string} jwtToken The JSON Web Token to use for authorization.
* @param {RequestInit} options Optional fetch options (method, body, etc.).
* @returns {Promise<any>} A promise that resolves with the API response data.
*/
async function fetchWithJwt(url, jwtToken, options = {}) {
if (!jwtToken) {
throw new Error('JWT token is required for authenticated requests.');
}
const headers = {
'Content-Type': 'application/json', // Default content type, can be overridden
'Authorization': `Bearer ${jwtToken}`,
...options.headers, // Allow overriding or adding more headers
};
const fetchOptions = {
...options,
headers,
};
try {
const response = await fetch(url, fetchOptions);
if (!response.ok) {
const errorBody = await response.text().catch(() => 'Unknown error');
throw new Error(`API Error: ${response.status} ${response.statusText} - ${errorBody}`);
}
return await response.json();
} catch (error) {
console.error('Error during authenticated fetch:', error);
throw error;
}
}
// Example Usage:
// const myJwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'; // Replace with your actual JWT
// const protectedApiUrl = 'https://api.example.com/user/profile';
// fetchWithJwt(protectedApiUrl, myJwt)
// .then(data => console.log('User profile:', data))
// .catch(error => {
// console.error('Failed to fetch profile:', error.message);
// if (error.message.includes('401')) {
// // Handle unauthorized, e.g., redirect to login or refresh token
// console.log('Token expired or invalid, please log in again.');
// }
// });
// Example with POST data:
// const newPost = { title: 'My New Post', content: 'Lorem ipsum...' };
// fetchWithJwt('https://api.example.com/posts', myJwt, {
// method: 'POST',
// body: JSON.stringify(newPost)
// }).then(data => console.log('Post created:', data))
// .catch(error => console.error('Error creating post:', error));
How it works: This `fetchWithJwt` function simplifies making authenticated API requests using JSON Web Tokens. It ensures that the `Authorization` header is correctly set with the `Bearer` scheme and the provided JWT token before making the `fetch` call. This pattern is standard for securing access to protected API endpoints, allowing developers to easily integrate authentication into their frontend or backend JavaScript applications. Error handling is included to catch network issues and non-OK HTTP responses.