Lesson 113 of 158 – Axios Headers
71%

Axios Headers

HTTP headers are used to send additional information with an API request. In React Native applications, Axios can send headers such as Content-Type, Accept, and Authorization.

Note: Headers are especially important when connecting a React Native application to a protected PHP REST API because authentication tokens are commonly sent through the Authorization header.

1. What are HTTP Headers?

HTTP headers contain additional information about an HTTP request or response.

Request
   ↓
Headers
   ↓
PHP REST API
   ↓
Response

Headers can describe the data format, authentication information, accepted response format and other request details.

2. Why Use Headers?

  • Send authentication tokens.
  • Specify request data format.
  • Specify accepted response format.
  • Send application-specific information.
  • Control how the server interprets a request.

3. Axios Request Configuration

Axios allows headers to be specified inside the request configuration object.

const response =
    await axios.get(
        API_URL,
        {
            headers: {
                "Accept":
                    "application/json"
            }
        }
    );

4. Accept Header

The Accept header tells the server what response format the client can accept.

headers: {
    "Accept":
        "application/json"
}

For a JSON REST API, application/json is commonly used.

5. Content-Type Header

The Content-Type header describes the format of the request body.

headers: {
    "Content-Type":
        "application/json"
}

This is commonly used when React Native sends JSON data to a PHP API.

6. Axios POST with Content-Type

const response =
    await axios.post(

        API_URL,

        {
            name: "Rahul",
            email: "rahul@example.com"
        },

        {
            headers: {
                "Content-Type":
                    "application/json"
            }
        }
    );

7. Authorization Header

The Authorization header is commonly used to send authentication credentials or tokens.

headers: {
    Authorization:
        `Bearer ${token}`
}

The server can read this token and verify the user's identity.

8. Bearer Token

JWT authentication commonly uses the Bearer authentication scheme.

Authorization:
Bearer eyJhbGciOiJIUzI1Ni...

The word Bearer is followed by the access token.

9. Axios GET with Authorization

const response =
    await axios.get(
        API_URL,
        {
            headers: {
                Authorization:
                    `Bearer ${token}`
            }
        }
    );

10. Axios POST with Authorization

const response =
    await axios.post(

        API_URL,

        {
            name: "Rahul",
            course: "React Native"
        },

        {
            headers: {
                Authorization:
                    `Bearer ${token}`
            }
        }
    );

11. Multiple Headers

const response =
    await axios.get(
        API_URL,
        {
            headers: {

                "Accept":
                    "application/json",

                "Content-Type":
                    "application/json",

                "Authorization":
                    `Bearer ${token}`
            }
        }
    );

12. Headers with Axios Instance

const api =
    axios.create({

        baseURL:
            "https://example.com/api",

        headers: {
            "Accept":
                "application/json"
        }

    });

Common headers can be configured once in an Axios instance.

13. Default Headers

Axios allows default headers to be configured for an instance.

const api =
    axios.create({

        baseURL:
            "https://example.com/api",

        headers: {
            "Accept":
                "application/json"
        }

    });

These headers can be used automatically for requests made through the instance.

14. Adding Authorization to an Axios Instance

const api =
    axios.create({

        baseURL:
            "https://example.com/api",

        headers: {
            Authorization:
                `Bearer ${token}`
        }

    });

For applications where the token changes after login, interceptors are often a better approach.

15. PHP Reading Authorization Header

The PHP API needs to read the Authorization header when JWT authentication is being used.

$headers =
    getallheaders();

$authorization =
    $headers['Authorization']
    ?? '';

16. Extracting the Bearer Token

$authorization =
    $headers['Authorization']
    ?? '';

if (
    !preg_match(
        '/Bearer\s+(.+)/i',
        $authorization,
        $matches
    )
) {

    http_response_code(401);

    echo json_encode([
        "success" => false,
        "message" =>
            "Authorization token required"
    ]);

    exit;
}

$token = $matches[1];

17. Headers and JWT Verification

After extracting the token, the PHP API can verify the JWT signature, expiration and claims.

Authorization
      ↓
Bearer Token
      ↓
Extract Token
      ↓
Verify JWT
      ↓
Identify User
      ↓
Allow API Request

18. Headers with PUT

const response =
    await axios.put(

        `${API_URL}?id=10`,

        {
            name: "Rahul Kumar",
            course: "TypeScript"
        },

        {
            headers: {
                "Content-Type":
                    "application/json",

                Authorization:
                    `Bearer ${token}`
            }
        }
    );

19. Headers with DELETE

const response =
    await axios.delete(

        `${API_URL}?id=10`,

        {
            headers: {
                Authorization:
                    `Bearer ${token}`
            }
        }
    );

DELETE requests can also require authentication and authorization.

20. Headers and API Security

  • Use HTTPS for API communication.
  • Do not put JWT tokens in URLs.
  • Use Authorization headers for access tokens.
  • Never send passwords in unnecessary headers.
  • Validate and verify tokens on the server.
  • Use appropriate authorization checks.

21. Headers with Query Parameters

Headers and query parameters can be used in the same Axios request.

const response =
    await axios.get(

        API_URL,

        {
            params: {
                search: "rahul",
                page: 1,
                limit: 10
            },

            headers: {
                Authorization:
                    `Bearer ${token}`
            }
        }
    );

22. Axios Headers with Error Handling

try {

    const response =
        await axios.get(
            API_URL,
            {
                headers: {
                    Authorization:
                        `Bearer ${token}`
                }
            }
        );

    console.log(
        response.data
    );

} catch (error) {

    if (error.response) {

        console.log(
            error.response.status
        );

        console.log(
            error.response.data
        );

    } else {

        console.log(
            "Network error"
        );
    }
}

23. Using Headers in a Reusable API Function

async function getProfile(
    token
) {

    const response =
        await axios.get(
            API_URL,
            {
                headers: {
                    Authorization:
                        `Bearer ${token}`
                }
            }
        );

    return response.data;
}

Reusable functions help keep API communication separate from UI components.

24. Axios Interceptors Preview

When many API requests need the same authentication header, Axios interceptors can automatically add the token.

api.interceptors.request.use(
    config => {

        config.headers.Authorization =
            `Bearer ${token}`;

        return config;

    }
);

Interceptors will be covered in detail in a later lesson.

25. Complete Axios API Instance with Headers

import axios from "axios";

const api =
    axios.create({

        baseURL:
            "https://example.com/api",

        timeout: 10000,

        headers: {
            "Accept":
                "application/json",

            "Content-Type":
                "application/json"
        }

    });

export default api;

This instance can be imported into different React Native screens.

26. Complete Authenticated GET Example

import axios from "axios";

const API_URL =
    "https://example.com/api/profile.php";

async function getProfile(token) {

    try {

        const response =
            await axios.get(
                API_URL,
                {
                    headers: {

                        "Accept":
                            "application/json",

                        "Authorization":
                            `Bearer ${token}`

                    }
                }
            );

        return response.data;

    } catch (error) {

        if (error.response) {

            console.log(
                error.response.status
            );

            console.log(
                error.response.data
            );

        } else {

            console.log(
                "Network error"
            );
        }

        throw error;
    }
}

27. Common Header Mistakes

  • Misspelling the header name.
  • Forgetting the Bearer prefix for JWT authentication.
  • Sending the token in the URL instead of the Authorization header.
  • Using an expired token.
  • Not sending Content-Type when required by the API.
  • Sending incorrect JSON data.
  • Not using HTTPS for sensitive communication.
  • Putting secrets directly into client-side application code.

28. Complete React Native Header Example

import React, {
    useState
} from "react";

import {
    View,
    Text,
    Button
} from "react-native";

import axios from "axios";

const API_URL =
    "https://example.com/api/profile.php";

export default function Profile() {

    const [profile, setProfile] =
        useState(null);

    const [message, setMessage] =
        useState("");

    async function loadProfile() {

        const token =
            "YOUR_ACCESS_TOKEN";

        try {

            const response =
                await axios.get(
                    API_URL,
                    {
                        headers: {

                            "Accept":
                                "application/json",

                            "Authorization":
                                `Bearer ${token}`

                        }
                    }
                );

            setProfile(
                response.data.data
            );

            setMessage("");

        } catch (error) {

            setMessage(
                error.response?.data?.message ||
                "Unable to load profile"
            );
        }
    }

    return (

        <View style={{
            padding: 20
        }}>

            <Button
                title="Load Profile"
                onPress={loadProfile}
            />

            <Text>
                {profile?.name || ""}
            </Text>

            <Text>
                {profile?.email || ""}
            </Text>

            <Text>
                {message}
            </Text>

        </View>
    );
}

In a real application, the token should come from the application's authentication/token storage system rather than being hard-coded.

29. Headers in Postman

The same headers used by React Native can be tested in Postman.

Authorization:
Bearer YOUR_TOKEN

Accept:
application/json

Content-Type:
application/json

Postman is useful for checking whether the PHP API correctly accepts authentication and content headers before connecting it to React Native.

30. Complete Axios Headers Flow

React Native
      ↓
     Axios
      ↓
Request Headers
      ↓
Authorization
Content-Type
Accept
      ↓
 PHP REST API
      ↓
Verify Headers
      ↓
Authenticate User
      ↓
Process Request
      ↓
 JSON Response
      ↓
 React Native

Understanding headers is essential before working with authenticated REST APIs. In the next lesson, we will learn how Axios handles API errors in more detail.

📌 Key Points

  • HTTP headers send additional information with API requests.
  • Accept describes the response format the client can accept.
  • Content-Type describes the request body format.
  • Authorization is commonly used for authentication.
  • JWT tokens are commonly sent as Bearer tokens.
  • Axios allows headers through the request configuration object.
  • Headers can be configured in an Axios instance.
  • Headers can be combined with query parameters.
  • Protected APIs should verify authentication and authorization on the server.
  • Do not put access tokens in URLs.
  • Use HTTPS when sending sensitive information.
  • Axios interceptors can automate common request headers.

🧠 Quick Quiz

Question: Which HTTP header is commonly used to send a JWT access token?