API calls returns Unauthorized

I have better auth setup on https://accounts.domain.com in production, for testing purposes When I hit /api/auth/get-session on another app, running in localhost, I get 401 unauthorized. I also have the multi domain setup like this
crossSubDomainCookies: {
enabled: process.env.NODE_ENV === "production",
domain:
(process.env.NODE_ENV === "production" &&
".accounts.domain.com") ||
undefined,
},
crossSubDomainCookies: {
enabled: process.env.NODE_ENV === "production",
domain:
(process.env.NODE_ENV === "production" &&
".accounts.domain.com") ||
undefined,
},
My BetterAuth ENV
BETTER_AUTH_SECRET=abc....
BETTER_AUTH_URL=https://accounts.domain.com
BETTER_AUTH_SECRET=abc....
BETTER_AUTH_URL=https://accounts.domain.com
Any idea why I get 401 though am logged in on the accounts.domain.com?
4 Replies
bekacru
bekacru12mo ago
how are you passing the session token?
Amazin' Sly
Amazin' SlyOP12mo ago
This is the localhost middlware.ts
import { NextResponse, type NextRequest } from "next/server";
import { AUTH_URL } from "./utils/config";


export async function middleware(request: NextRequest) {
const response = await fetch(`${AUTH_URL}/api/auth/session`, {
method: "GET",
});

if (!response.ok) {
return NextResponse.redirect(
new URL(
`${AUTH_URL}/auth/sign-in`,
request.url
)
);
}

const sessionData = await response.json();

if (!sessionData || !sessionData.session) {
return NextResponse.redirect(
new URL(
`${AUTH_URL}/auth/sign-in`,
request.url
)
);
}

return NextResponse.next();
}

export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};
import { NextResponse, type NextRequest } from "next/server";
import { AUTH_URL } from "./utils/config";


export async function middleware(request: NextRequest) {
const response = await fetch(`${AUTH_URL}/api/auth/session`, {
method: "GET",
});

if (!response.ok) {
return NextResponse.redirect(
new URL(
`${AUTH_URL}/auth/sign-in`,
request.url
)
);
}

const sessionData = await response.json();

if (!sessionData || !sessionData.session) {
return NextResponse.redirect(
new URL(
`${AUTH_URL}/auth/sign-in`,
request.url
)
);
}

return NextResponse.next();
}

export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};
bekacru
bekacru12mo ago
if you're logged in at account.domain.com the cookie isn't stored on localhost and if it's stored it's only sent to account.domain.com
Amazin' Sly
Amazin' SlyOP12mo ago
Okay makes sense... During development, I will get the accounts.domain.com running locally as well Thanks. If I can set sameSite to "None" on the cookie, I can share it with localhost, right? I saw solutions on how to share cookie across multiple domains, but I can't set sameSite to None on better-auth to achieve that

Did you find this page helpful?