#How to validate jwt token (custom auth) before sending the request to my api?
1 messages · Page 1 of 1 (latest)
To validate a JWT token before sending a request to your API, you can create a middleware function that checks the validity of the token. Here's an example of how you can do this:
export const SessionMiddleware = defineMiddleware({
global: true,
async handler(req: NextRequest) {
const accessToken = req.cookies.get(StorageKey.AccessToken)?.value;
const refreshToken = req.cookies.get(StorageKey.RefreshToken)?.value;
if (!accessToken || !refreshToken) return;
const { exp } = decodeJwt<TokenPayload>(accessToken) ?? {};
const isValid = dayjs().isBefore(unix(exp!), 'minute');
if (isValid) return;
try {
console.log('INFO: Start refresh tokens');
const { refreshSession } = sessionApi();
const session = await refreshSession(refreshToken);
console.log('INFO: End refresh tokens', session);
} catch (error) {
// handle error
}
}
});
In this example, the middleware function checks if the access token and refresh token exist. If they do, it decodes the JWT and checks if the token is still valid. If the token is not valid, it attempts to refresh the session.
This middleware function can be used in your Next.js application to validate the JWT token before sending a request to your API. If the token is not valid, the function will attempt to refresh the session and update the token.
Please note that this is a general example and you might need to adjust it according to your specific needs and the libraries you are using.
You can find more information about this in the Github Issue (https://github.com/vercel/next.js/issues/54266) from the knowledge sources.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@sick venture kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
Yes, setting cookies in a server action can cause the entire app to reload, which may result in a flicker. This is especially noticeable when the layout is using a custom font that also needs to load. This behavior is due to the fact that when cookies are mutated inside an Action, it's expected to re-render the app because there could be data that depends on cookies.
However, it's important to note that this behavior is more noticeable in development mode. In production, the glitch is only apparent when turning on highlighting.
Here's a relevant discussion from the Github Issue (https://github.com/vercel/next.js/issues/50163) in the knowledge sources:
**Comment by MEMBER (0 upvotes, 0 downvotes)**:
> This appears as a render glitch most noticeable when the layout is using a custom font that also needs to load.
That's dev only as we ditch all the cache of CSS resources when a server refresh is triggered, which should be fine. Are you seeing that on prod as well?
Also, if cookies are mutated inside an Action, it's expected to re-render the app because there could be data that depends on cookies.
The user also questioned whether the entire app should reload every time any cookie is set or mutated, as in some cases, a cookie should change frequently, with every click. This suggests that the behavior might not be ideal for all use cases.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@sick venture kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
It depends on your specific use case. If the flicker or full app reload is causing a significant disruption to your user experience, you may want to consider alternative strategies for managing state or triggering updates in your application.
However, as mentioned in the Github Issue (https://github.com/vercel/next.js/issues/50163), this behavior is more noticeable in development mode and less so in production. If the flicker is not causing a significant issue in your production environment, it may be something you can ignore during development.
Remember, the reason for the full app reload is because mutating cookies could potentially change data that your app depends on, so the app re-renders to ensure the data is up-to-date. If you're frequently changing cookies that don't impact critical app data, you might want to reconsider your app's architecture to avoid unnecessary full app reloads.