Setting Headers with Axios in Node JS
Tags: webdev, javascript, tutorial, node
Published: 2024-02-18 23:45:58

In this article we are going to learn how to set headers with Axios. Here is what we are going to learn in this article

* Setting up the development Environment and Installing Axios
    
* Sending Basic GET and POST requests with Axios
    
* Advanced Header configuration with Axios
    
* Set default headers globally for all Axios requests
    
* Setting Custom Headers for individual requests
    
* Practical code examples: Auth Tokens and Content Type Modifications
    
* Handling CORS error in development
    
* Introducing Axios Interceptors for enhanced control
    

## Setting up the development Environment and Installing Axios

In this section we are going to install the axios and set up our development environment

### Prerequisites

1. Install Node Js: You need Node JS installed in your machine
    
2. Init your Node Project: Start a new project with `npm init`
    
3. Install Express: install express js and open the project and index.js file in VScode
    

### Installing Axios

Install axios to your project by

```bash
npm install axios
```

## Basic GET and POST request with axios

In this article we are focusing on server side implementation of axios. You can use a GET request to request data from an external api into your server

### Get Request

to send a GET request type the below code in your `index.js` file in your express server.

```javascript
const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;

app.get('/fetch-data', (req, res) => {
  axios.get('https://jsonplaceholder.typicode.com/posts')
    .then(response => {
      res.send(response.data);
    })
    .catch(error => {
      res.send('Error occoured when fetching data');
      console.error('An error occoured when fetching data', error);
    });
});

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
```

### POST Request

You can send a POST request to an external server to send data to that server.

Here is how you can send a POST request.

```js
app.post('/create-post', (req, res) => {
  axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'Hello World',
    body: 'This is a new post created by my server.',
    userId: 1,
  })
  .then(response => {
    res.send(response.data);
  })
  .catch(error => {
    res.send('Error creating a post');
    console.error('There was an error!', error);
  });
});
```

## Advanced Header configuration with Axios

Using Advanced header configuration allows us to control the HTTP requests headers, and enables us to customize headers for specific situations like authentication, content management and many more

## Set default headers globally for all Axios requests

Using Axios you can set a global setting that would allow us to send the same headers for all the requests that are made.

This is helpful in automation of headers that are common across all the requests that are made, an example would be `Content-Type` or auth tokens

Here is the 2 step process for setting Global headers in Axios

### Step 1: Creating an axios instance

You can create an instance of axios to configure the global settings. Then use the instance across your application in order to send requests.

```js
const axios = require('axios');

// creating an Axios instance
const axiosInstance = axios.create({
  baseURL: 'https://api.timbucktoo.com',
});

// Setting the default headers
axiosInstance.defaults.headers.common['Authorization'] = `Bearer YOUR_ACCESS_TOKEN`;
axiosInstance.defaults.headers.post['Content-Type'] = 'application/json';
```

What are we doing here?

* We have an Axios instance configured with a `baseURL`
    
* We have set default headers for all requests (\`Authorization\`)
    
* and for POST requests (\`Content-Type\`)
    

### Step 2: Using the instance

Here is how you can use the instance that we just created to send requests with pre set defaults

```js
axiosInstance.get('/user')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
```

## Setting Custom Headers for Individual Requests

Default header are useful for application wide sending of requestsm but you might also need to send specific headers with individual requests.

You can set custom headers for indivual requsets in axios as well. Here are 2 ways you can do that

### Way 1:  Setting custom headers in a request

By using the `headers` property. You can directly specify the custom headers in your configuration Object like so

```js
axios.get('https://api.example.com/user', {
  headers: {
    'X-Custom-Header': 'value',
    'Authorization': 'Bearer ANOTHER_ACCESS_TOKEN' // Overrides any defaults that are set
  }
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
```

What are we doing here?

* We are making a GET request with custom headers
    
* These a `X-Custom-Header` and an `Auth token`
    
* These override any defealts that may or may not have been set
    

### Way 2: Dynamic headers

Some time you need to headers to be dynamically applied at runtime.  For these use cases axios allows you to dynamically comute header just before making a request

For example: If the auth token changes frequently and is dependent on which user is sending the data to the server. Auth token has to be retrived from a third party API or some thing like that

here is how you can do this

```js
function getToken() {
  // This function retrieves the current user's token from somewhere Dynamically
  return 'DYNAMIC_ACCESS_TOKEN';
}

axios.get('https://api.some-sample-website.com/user', {
  headers: {
    'Authorization': `Bearer ${getToken()}`
  }
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
```

## Practical code examples: Auth Tokens and Content Type Modifications

Let us look at some practical and real life examples of setting custom headers with axios these include handling auth tokens and content type modifications

### Handling auth tokens

the most commonly used auth tokens are JWT (that is JSON web tokens), these are generally send in the `Authorization` header.

here is how you can do this

#### Setting auth token for a single request

```js
const axios = require('axios');

// Function to make a request with an auth token
function fetchUserData(authToken) {
  axios.get('https://api.some-sample-website.com/data', {
    headers: {
      'Authorization': `Bearer ${authToken}`
    }
  })
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
}

// Example usage
const userToken = 'your_user_token_here';
fetchUserData(userToken);
```

In this example we are demonstrating how to set a auth token header in a single request in server side with axios, node and expressjs

#### Automatically adding auth tokens with axios

for requests that require auth token with every request, we can use something called as interceptors.

We are going to learn more about them below. but for now consider an example on how to use them

```js
const axios = require('axios');

// creating the Axios instance
const apiClient = axios.create({
  baseURL: 'https://api.some-sample-website.com',
});

// retive the auth token from somewhere
function getAuthToken() {
  // Retrieve and return the auth token from third party api or some other place etc.
  return 'your_auth_token_here';
}

// A request interceptor to include the auth token in every request
apiClient.interceptors.request.use(config => {
  const token = getAuthToken();
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
}, error => Promise.reject(error));

// Now, when you are sending data apiClient, each request will automatically have the auth token
apiClient.get('/user')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
```

What are we doing here?

Basically we are using an interceptor to attach a auth token every time a request is being made that's it

### Modifying content type  with axios

With the `Content-Type` header we can inform the server, what type of data are we sending.

Is it JSON data or plain text or any other type and as such this is an important header.

When you are changing the data type that is being sent to the server you need to modify the `Content-Type` header.

Here is how you can do that with axios

#### Setting content type for a single request

```js
const axios = require('axios');

axios.post('https://api.some-sample-website.com/data', {
  property1: 'value-abcd',
  property2: 'value-efgi'
}, {
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
```

What are we doing here?

We are explicitly setting `Content-Type` for the post request to `application/json`

#### Global configuration for Content-Type

you can also set the content type globally to set the header for all requests.

Here is an example where we are setting the content-type to application/json for all the requests that are being made to the server

```js
const axios = require('axios');

// Creating the Axios instance with a default Content-Type
const apiClient = axios.create({
  baseURL: 'https://api.some-sample-website.com',
  headers: {
    'Content-Type': 'application/json'
  }
});

// Use apiClient for making requests
apiClient.post('/data', {
  property1: 'value-abcd',
  property2: 'value-efgh'
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
```

## Handling CORS error in development and Production

CORS means Cross Origin Resource Sharing. This is a security feature that is implement by all major browsers in order to stop malicious website from accessing data from another domain without their permission

### What is CORS error?

CORS issues arises when you have an app that is running in the browser and making requests to a server that is on another domain

The browsers stops such requests unless the server indicates with headers that is willing to accept these requests (That is the server is willing to accept requests from the clients origin)

### Handling CORS in development

During development it is common to encounter CORS error, this is because the client and server both are running om different ports or domains

Here are some of the methods you can use to mitigate this error with the help of axios

#### Step 1 Using a Middleware proxy

you can use a middleware proxy to proxy requests to the server. this involves configuring the development server to that are aimed at a aimed at a specific path/paths to the backend server and other requests to the server running on the local machine

```json
"proxy": "http://localhost:3000",
```

here we are proxying the requests

#### Step 2 CORS Middleware in Backend

In backend frameworks such as express js there is a dedicated middleware to enable the CORS functionality

## Introducing Axios Interceptors for enhanced control

Interceptors allows you to intercept and manipulate a HTTP request and response before they are handled by `catch` or `then`

This capcability can be used in a variety of use cases most notebly

* Setting headers dynamically
    
* Logging requests to console before they are being made
    
* transforming data before it reaches other parts of your app
    
* handling error and
    
* other such tasks
    

There are two kinds of interceptors

### 1\. Request Interceptors

Request intereceptors are used to modify a request before it is being made. Using request interceptors you can modify the request configuration object and manipulate configuration such as header URL or parameteres

You can also set global headers or perform logging with the help of request interceptors

Request Interceptors are called just before a HTTP request is being made by the server.

### Response Interceptors

As the name suggeests the response interceptors are invoked just after a response is recieved by the server but before the promise is resolved.

Response interceptors can be used to globally transform the dataa, manage application wide errors, handle tasks such as error handling and analytics based response

### Practical Use Case for Axios Interceptors

1. **Authentication:** Automatically attach auth tokens to outgoing requests
    
2. **Logging:** Logging a request to console just before it is being made
    
3. **Error Handling:** Implement error handling on a application wide basis
    
4. **Data Transformation:** Process the data in the required format before sending.
    
5. **Loading Headers:** Show a indication when a request is starting and hide it when the request is complete
    

![DeadSimpleChat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhq1nm6nphor5ojhrd4s.png)



##   
Need [Chat API](https://deadsimplechat.com/) for your website or app

[DeadSimpleChat](https://deadsimplechat.com/) is an Chat API provider

* Add Scalable Chat to your app in minutes
    
* 10 Million Online Concurrent users
    
* 99.999% Uptime
    
* Moderation features
    
* 1-1 Chat
    
* Group Chat
    
* Fully Customizable
    
* Chat API and SDK
    
* Pre-Built Chat
    


![Metered TURN servers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/452j4alhymdzqohgxzir.png)

## [Metered TURN servers](https://www.metered.ca/stun-turn)

1. **Global Geo-Location targeting:** Automatically directs traffic to the nearest servers, for lowest possible latency and highest quality performance. less than 50 ms latency anywhere around the world
    
2. **Servers in 12 Regions of the world:** Toronto, Miami, San Francisco, Amsterdam, London, Frankfurt, Bangalore, Singapore,Sydney, Seoul
    
3. **Low Latency:** less than 50 ms latency, anywhere across the world.
    
4. **Cost-Effective:** pay-as-you-go pricing with bandwidth and volume discounts available.
    
5. **Easy Administration:** Get usage logs, emails when accounts reach threshold limits, billing records and email and phone support.
    
6. **Standards Compliant:** Conforms to RFCs 5389, 5769, 5780, 5766, 6062, 6156, 5245, 5768, 6336, 6544, 5928 over UDP, TCP, TLS, and DTLS.
    
7. **Multi‑Tenancy:** Create multiple credentials and separate the usage by customer, or different apps. Get Usage logs, billing records and threshold alerts.
    
8. **Enterprise Reliability:** 99.999% Uptime with SLA.
    
9. **Enterprise Scale:** With no limit on concurrent traffic or total traffic. Metered TURN Servers provide Enterprise Scalability
    
10. **50 GB/mo Free:** Get 50 GB every month free TURN server usage with the Free Plan
    
11. Runs on port 80 and 443
    
12. Support TURNS + SSL to allow connections through deep packet inspection firewalls.
    
13. Support STUN
    
14. Supports both TCP and UDP