I'm in the process of developing a JWT authorization code flow using Next.js and NestJS.
Below is the POST request being sent from the frontend to the backend server:
const response = await fetch(
'http://localhost:4000/auth/42/callback?code=' + code, { // The code parameter is received from the OAuth server
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
}
);
Once the backend receives this request, it processes it by generating a JWT and sending it back to the frontend via the response
.
@Post('42/callback')
async Callback(@Query('code') code: string, @Res({passthrough: true}) res) {
if (!code) {
res.status(400).send('Missing code');
return;
}
try {
const response = await this.authService.exchangeCodeForToken(code);
const jwt = await this.authService.handleCallback(response);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.cookie('jwt', jwt, {
sameSite: 'strict'
});
res.status(200).send();
} catch (error) {
console.error(error);
res.status(500).send('Internal server error');
}
}
Although the browser successfully sets the jwt
cookie, there seems to be a delay in its availability for immediate use.
import jwtDecode from 'jwt-decode';
import { useCookies } from 'react-cookie';
const [ cookies ] = useCookies();
const jwt = cookies.jwt;
const jwtPayload: any = jwtDecode(jwt); // At this point, jwt is returning as undefined
I've inspected the Network Profiler in the browser but haven't been able to identify any noticeable latency issues. https://i.stack.imgur.com/pEGRV.png