Next.js Discord

Discord Forum

If I have a function that I want it to run on the client and the server they share the same code

Unanswered
Seppala Siberian Sleddog posted this in #help-forum
Open in Discord
Seppala Siberian SleddogOP
I have this function that I want to get the access token from the cookie if the source is server and I want it to get the token from the local storage if it's being run on the client I'm using dynamic imports but I'm getting warning from NextJS
import type { RequestCookie } from 'next/dist/compiled/@edge-runtime/cookies';

export type Source = 'client' | 'server';

export interface BaseConstructorAuthParams {
  source?: Source;
}
export default class BaseAuth {
  protected accessToken: string;
  protected baseUrl: string = process.env.NEXT_PUBLIC_DOMAIN_NAME as string;

  constructor({ source = 'client' }: BaseConstructorAuthParams) {
    if (source === 'client')
      this.accessToken = localStorage.getItem('access_token') as string;
    else this.accessToken = '';
  }

  protected getAuthHeader() {
    return { Authorization: `Bearer ${this.accessToken}` };
  }

  async initializeServerSide() {
    const { cookies } = await import('next/headers');
    const token = cookies().get('access_token') as RequestCookie;
    this.accessToken = token.value;
    return Promise.resolve(this);
  }
}

The error saying static pages can't be generated.

0 Replies