Skip to content

Instantly share code, notes, and snippets.

@walosha
Last active May 17, 2024 00:52
Show Gist options
  • Save walosha/b4654b7e627574a97fe62cb545d6d340 to your computer and use it in GitHub Desktop.
Save walosha/b4654b7e627574a97fe62cb545d6d340 to your computer and use it in GitHub Desktop.
You can use Axios interceptors to automatically append the bearer token from local storage to all outgoing requests. Here's how you can set it up:
```javascript
import axios from 'axios';
// Create an instance of axios
const axiosInstance = axios.create();
// Add a request interceptor
axiosInstance.interceptors.request.use(
config => {
// Get the token from local storage
const token = localStorage.getItem('token');
// If a token exists, add it to the request headers
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => {
// Do something with request error
return Promise.reject(error);
}
);
export default axiosInstance;
```
With this setup:
- The interceptor intercepts all outgoing requests before they are sent.
- It retrieves the token from local storage.
- If a token exists, it adds it to the request headers with the format `"Bearer <token>"`.
- If there's an error with the request, it rejects the promise with the error.
Now, whenever you make a request using `axiosInstance`, the bearer token will be automatically added to the request headers if it exists in local storage. For example:
```javascript
import axiosInstance from './axiosInstance';
axiosInstance.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
```
Make sure to replace `'token'` with the key under which your token is stored in local storage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment