'Next.js middleware to set Axios header
I'm trying to use Next 12 to add an Authorization header to my Axios instance with middleware. However, it doesn't look as though the header is actually being passed into the requests within getServerSideProps, and I can't figure out why.
This is what my middleware looks like:
import { Client } from 'lib/api/config';
import { AUTH } from 'modules/auth/api/endpoints';
import { NextRequest, NextResponse } from 'next/server';
import { API_ROOT_URL, AUTH_TOKEN_COOKIE_KEY } from 'utils/constants/constants';
const middleware = async (req: NextRequest) => {
const token = req.cookies[AUTH_TOKEN_COOKIE_KEY];
const url = req.nextUrl.clone();
const response = await fetch(`${API_ROOT_URL}${AUTH.validateToken}`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
if (data.statusCode !== 200 && !url.pathname.includes('/login')) {
url.pathname = '/login';
return NextResponse.redirect(url);
} else {
Client.defaults.headers['Authorization'] = `Bearer ${token}`;
}
};
export default middleware;
As you can see I'm storing the token in a cookie, getting the token from the req.cookies property when a request is made, validating the token, and if it's valid I'm adding it to Client.defaults.headers. However, if I make a request to a route I'm getting a 403 error saying that there is no auth header found. Is there something I need to change up to get this going?
As a side not, we're using the WordPress REST API, coupled with this plugin for JWT Authentication:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
