Storing ab access token in memory server-side in NextJS

How can i store a token in-memory server-side in a Next.JS project? I tried doing this:
export let accessToken: AccessToken | undefined;

export async function getAccessToken(): Promise<string | undefined> {
console.log(accessToken);
if (accessToken && +accessToken.expires_on > Date.now() / 1000) {
return accessToken.access_token;
} else {
try {
const token = await client.auth.getToken(clientId, clientSecret);
if (token.ok) {
accessToken = token.data;
return token.data.access_token;
}
} catch (err) {
}
return undefined;
}
}
export let accessToken: AccessToken | undefined;

export async function getAccessToken(): Promise<string | undefined> {
console.log(accessToken);
if (accessToken && +accessToken.expires_on > Date.now() / 1000) {
return accessToken.access_token;
} else {
try {
const token = await client.auth.getToken(clientId, clientSecret);
if (token.ok) {
accessToken = token.data;
return token.data.access_token;
}
} catch (err) {
}
return undefined;
}
}
then i have a function that gets it, or refreshes it depending on expiration time... the problem however is that it goes back to undefined, after being set for some reason. lets say i have this API route handler to test getting a token: /api/test/:
import { getAccessToken } from '@/lib/vipps';

export const dynamic = 'force-dynamic';

export async function GET() {
const token = await getAccessToken();

return Response.json({
retrivedToken: token,
});
}
import { getAccessToken } from '@/lib/vipps';

export const dynamic = 'force-dynamic';

export async function GET() {
const token = await getAccessToken();

return Response.json({
retrivedToken: token,
});
}
if i curl http://localhost:3000/api/test i will get the same token back and i will get the stored one until go to different routes, and then come back to curling the test it is undefined. what am i missing here? maybe it gets redeclared somehow?
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server