supabase: "supabase.auth.getUser()" is returning a null user value in nextjs middleware.ts using @supabase/supabase-js @supabase/ssr only
Bug report
- I confirm this is a bug with Supabase, not with my own application.
- I confirm I have searched the Docs, GitHub Discussions, and Discord.
Describe the bug
const { data, error } = await supabase.auth.getUser();
console.log("user : ", error); //getting an error
error, even if I followed everything in doc. https://supabase.com/docs/guides/auth/server-side/nextjs
[AuthSessionMissingError: Auth session missing!] {
__isAuthError: true,
name: 'AuthSessionMissingError',
status: 400,
code: undefined
}
my observation:
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
console.log("name ==>", name);
console.log("nameValue ==>", request.cookies.get(name)?.value);
return request.cookies.get(name)?.value;
},
set(name: string, value: string, options: CookieOptions) {
request.cookies.set({
name,
value,
...options,
});
response = NextResponse.next({
request: {
headers: request.headers,
},
});
response.cookies.set({
name,
value,
...options,
});
},
remove(name: string, options: CookieOptions) {
request.cookies.set({
name,
value: "",
...options,
});
response = NextResponse.next({
request: {
headers: request.headers,
},
});
response.cookies.set({
name,
value: "",
...options,
});
},
},
}
);
logs:
name ==> sb-yelbdeiefeqnignhtxkc-auth-token
nameValue ==> undefined
name ==> sb-yelbdeiefeqnignhtxkc-auth-token.0
nameValue ==> undefined
real name of cookie is something different
I am using Google and github as provider. and this is what my code look like full repo an opensource portfolio & resume builder
src/middleware.ts
import { updateSession } from "@/utils/supabase/middleware";
import { type NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
return await updateSession(request);
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
"/((?!_next/static|_next/image|favicon.ico|p|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
],
};
src\utils\supabase\client.ts
import { createBrowserClient } from "@supabase/ssr";
export function createClient() {
return createBrowserClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
);
}
src\utils\supabase\server.ts
"use server";
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";
export default async function createClient() {
const cookieStore = cookies();
return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return cookieStore.get(name)?.value;
},
set(name: string, value: string, options: CookieOptions) {
try {
cookieStore.set({ name, value, ...options });
} catch (error) {
// The `set` method was called from a Server Component.
// This can be ignored if you have middleware refreshing
// user sessions.
}
},
remove(name: string, options: CookieOptions) {
try {
cookieStore.set({ name, value: "", ...options });
} catch (error) {
// The `delete` method was called from a Server Component.
// This can be ignored if you have middleware refreshing
// user sessions.
}
},
},
}
);
}
src\utils\supabase\middleware.ts
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";
export async function updateSession(request: NextRequest) {
let response = NextResponse.next({
request: {
headers: request.headers,
},
});
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
console.log("name ==>", name);
console.log("nameValue ==>", request.cookies.get(name)?.value);
return request.cookies.get(name)?.value;
},
set(name: string, value: string, options: CookieOptions) {
request.cookies.set({
name,
value,
...options,
});
response = NextResponse.next({
request: {
headers: request.headers,
},
});
response.cookies.set({
name,
value,
...options,
});
},
remove(name: string, options: CookieOptions) {
request.cookies.set({
name,
value: "",
...options,
});
response = NextResponse.next({
request: {
headers: request.headers,
},
});
response.cookies.set({
name,
value: "",
...options,
});
},
},
}
);
const { data, error } = await supabase.auth.getUser();
console.log("user : ", error);
// refreshing the auth token
const {
data: { user },
} = await supabase.auth.getUser();
if (
!user &&
request.nextUrl.pathname !== "/signin" &&
request.nextUrl.pathname !== "/"
) {
return NextResponse.redirect(new URL("/signin", request.url));
}
return NextResponse.next({
request: {
headers: request.headers,
},
});
}
src\app\auth\callback\route.ts
import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get("code");
// if "next" is in param, use it as the redirect URL
const next = searchParams.get("next") ?? "/";
if (code) {
const cookieStore = cookies();
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
get(name: string) {
return cookieStore.get(name)?.value;
},
set(name: string, value: string, options: CookieOptions) {
cookieStore.set({ name, value, ...options });
},
remove(name: string, options: CookieOptions) {
cookieStore.delete({ name, ...options });
},
},
}
);
const { error } = await supabase.auth.exchangeCodeForSession(code);
if (!error) {
return NextResponse.redirect(`${origin}${next}`);
}
}
// return the user to an error page with instructions
return NextResponse.redirect(`${origin}/auth/auth-code-error`);
}
onClick function signinWithSocial(“google” | “github”)
async function signinWithSocial(provider: Provider) {
const supabase = await createClient();
const { data, error } = await supabase.auth.signInWithOAuth({
provider: provider,
options: {
redirectTo: `${location.origin}/auth/callback?next=${location.origin}/app`,
},
});
if (error) {
console.error(error);
}
console.log(data);
}
To Reproduce
Steps to reproduce the behavior, please provide code snippets or a repository:
- Go to https://supabase.com/docs/guides/auth/server-side/nextjs follow the guide
- use google social login
- check the user value in middleware its null
- See error
Expected behavior
in the middleware i should get the user value, by which i can check and redirect someone if they are not loged in
Screenshots
If applicable, add screenshots to help explain your problem.
System information
- OS: [ Windows]
- Browser (if applies) [brave]
- Version of supabase-js:
- “@supabase/ssr”: “^0.3.0”, “@supabase/supabase-js”: “^2.43.1”,
- Version of Node.js: [v20.11.0]
Additional context
I have setuped oauth provider in supabase dashboard successfully, so that wont be any problem
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 8
- Comments: 28 (4 by maintainers)
this is absolutely correct ans make sure about this option
Make sure you have “Confirm Email” setting in Supabase->Authentication->Providers->Email turned off.
As long as this setting is ON, the auth-token cookie won’t be set unless the user confirms the email through the confirmation link received on mail
@Hallidayo The issue still exists with
next": "^15.0.3and@supabase/ssr": "^0.5.1"and@supabase/supabase-js": "^2.46.1.The user in middleware always returns null with Google provider and it returns to sign-in page
Fixed it by using only the @supabase/ssr library and not the @supabase/supabase-js at all. They are just not compatible with each other. I guess one could write a custom storage to make it work with cookies instead of localStorage but switching lib is an easier solution imo
Thanks @tomavanc updating matcher with
manifest.webmanifestfixed the issue.Run into the same issue. Confirmed all code is similar to what is described here (https://supabase.com/docs/guides/auth/server-side/nextjs)
When we await the user in
middleware.ts, we get some weird results. One request returns the user, the next returnsnull. Over and over again.If the user is null, it is actually an error being return from the
getUserfunction.As we log the cookies which are being set in the
getAllmethod, we see that cookies likeaccess_tokenandsb_...are present on a request. But the next request returns an empty array which then triggers the message above I guess.Using these versions
EDIT
Typical that you find it after you post on Github. We saw some requests came from our
PWAfunctionality, which triggered ourupdateSessionmiddleware with no cookies. My fix was to update thematcherconfig to block out the specificmanifestfile.Same here, running Next 15.0.2 with supabase-js in only client mode
@Hallidayo Yes I’m still experiencing the issue, nextjs version 14.2.6
In my case
removing export
const dynamic = 'force-static'from layout resolve issue