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);
}
},
},
});
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
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!
8 Replies
KiNFiSH
KiNFiSH5d ago
You can use bearerr plugin for handling bearer authentication
vijayatk3
vijayatk3OP5d ago
@KiNFiSH im using Next js But I'm getting this error: ReferenceError: localStorage is not defined
KiNFiSH
KiNFiSH4d ago
can you please try with for safe ignoring -
token: () => {
if (typeof window === 'undefined') return "";
return localStorage.getItem("bearer_token") || "";
}
token: () => {
if (typeof window === 'undefined') return "";
return localStorage.getItem("bearer_token") || "";
}
plus it is react package which means it is bundled with client files and it is not sth that should run on the server instead run on browser/client
Omicrxn
Omicrxn4d ago
actually i was getting the same issue on sveltekit, and in the docs it says to put auth-client under lib/ so maybe it should be updated on the docs: https://www.better-auth.com/docs/integrations/svelte-kit#create-a-client
SvelteKit Integration | Better Auth
Integrate Better Auth with SvelteKit.
vijayatk3
vijayatk3OP4d ago
@KiNFiSH Hi, I try the safe ignoring not working but it not throwing error ReferenceError: localStorage is not defined I also try the "use client" in auth-client.ts file in next js Note: the auth-client.ts file is under the /lib folder
KiNFiSH
KiNFiSH4d ago
So does that mean you are seeing the log on server ?
Ping
Ping2d ago
It probably just means you're using the authClient in a server enviroment

Did you find this page helpful?