Home > database >  Add default axios header after login nextjs
Add default axios header after login nextjs

Time:01-18

I'm using Next.js for my app, and currently have an API route that sets a JWT as a cookie. Throughout the app, I'm using Axios to fetch all of my data from external APIs, and after a user logs in I need to set that cookie as a default request header on every API call to make sure that a user has been authenticated. The basic flow is like this:

The login form sends a post request to my API route at /api/auth/login, passing the username and password and returning the JWT, and setting it as a cookie. Once the idToken cookie has been set I need to add that as an authentication header to every API request within my Axios instance, seen as adapter here. How can I go about getting this done?

My handle login function:

const handleLogin = async (values: ValuesProps) => {
    const response = await axios.post('/api/auth/login', values);

    if (response.status !== 200) {
      throw new Error(response.statusText);
    }
};

Which speaks to api/auth/login:

import { NextApiRequest, NextApiResponse } from 'next';
import { setCookie, parseCookies } from 'nookies';
import { adapter } from 'utils/api/config';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method !== 'POST') {
    res.status(500).json('Only POST requests allowed at this route.');
  } else {
    const { data } = await adapter.post(AUTH.login, JSON.stringify(req.body));
    const cookies = parseCookies();

    setCookie({ res }, 'idToken', data.token, {
      maxAge: 30 * 24 * 60 * 60,
      path: '/',
    });

    api.defaults.headers.Authorization = `Bearer ${cookies['idToken']}`

    res.status(200).json(data);
  }
};

export default handler;

As you see here I tried adding adapter.defaults.headers.Authorization as a global default, but I'm not seeing it in my request headers. What's the best way to go about setting this globally?

CodePudding user response:

You can set default header to all axios request by command:

const token = getCookie('token')
axios.defaults.headers.common["idToken"] = token

CodePudding user response:

You could use axios.create. It is a factory that creates new instances of axios. So you write a function

import axios from "axios";

export const axiosInstance = async () =>{
  // you need to be careful in next.js for adding cookies.
  // You could be on the server or on client. this code will work for client assuming that you will be using on client side
  // I belive you are using `parser` to get cookies. get the token
  const yourToken="whatever"
  const axiosClient = axios.create({
      baseURL: 'baseUrlHere',
      timeout: 1000,
      headers: {
          'Accept': 'application/vnd.GitHub.v3 json',
          // this is how u set in your code
          'Authorization': `Bearer ${cookies['idToken']}`
           }
   });    
   return axiosClient    
}

Then import this in anywhere you want to use:

 const {data}=await axiosInstance().post("/auth")

Technically this should work

  •  Tags:  
  • Related