Next.js Discord

Discord Forum

Storing a variable in memory server-side in Next.JS

Unanswered
Chartreux posted this in #help-forum
Open in Discord
ChartreuxOP
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;
  }
}
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,
  });
}

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