How to set Bearer token in Next.js

Hello Everyone,

import { createAuthClient } from 'better-auth/react';

export const {
  signIn,
  signUp,
  signOut,
  useSession,
  sendVerificationEmail,
  forgetPassword,
  resetPassword,
} = createAuthClient({
  fetchOptions: {
    auth: {
      type: "Bearer",
      token: () => localStorage.getItem("bearer_token") || ""
    },
    onSuccess: (ctx) => {
      const authToken = ctx.response.headers.get('set-auth-token');
      if (authToken) {
        localStorage.setItem('bearer_token', authToken);
      }
    },
  },
});

But I'm getting this error:

ReferenceError: localStorage is not defined


I believe it's because auth-client.ts is being run on the server side, where localStorage is unavailable.

Any help is appreciated!
Was this page helpful?