Next.js Discord

Discord Forum

Why doesn't middleware file do its job in this case?

Answered
American Pipit posted this in #help-forum
Open in Discord
American PipitOP
I'm trying to add authorization through the middleware.ts file, but it doesn't seem to work on the path that I added in the matcher for some reason. When I am on '/jobs' without any authentication (no token, no session), it just stays on that path. This is the code in question:
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs';
import { NextResponse } from 'next/server';

import type { NextRequest } from 'next/server';
import type { Database } from '../types';

export async function middleware(req: NextRequest) {
    const res = NextResponse.next();
    const supabase = createMiddlewareClient<Database>({ req, res });
    const session = await supabase.auth.getSession();

    if (!session) {
        return NextResponse.redirect(new URL('/login', req.url));
    }

    return res;
}

export const config = {
    matcher: '/jobs',
};
Answered by not-milo.tsx
Cause your using the returned value of getSession in a wrong way.

(method) GoTrueClient.getSession(): Promise<{
    data: {
        session: Session;
    };
    error: null;
} | {
    data: {
        session: null;
    };
    error: AuthError;
} | {
    data: {
        session: null;
    };
    error: null;
}>


This is the method signature and it's return type. As you can see the session is inside a data key. You would use it like this:

const {
  data: { session },
} = await supabase.auth.getSession()

if (!session) {
  return NextResponse.redirect(new URL('/login', req.nextUrl));
}
View full answer

16 Replies

Cause your using the returned value of getSession in a wrong way.

(method) GoTrueClient.getSession(): Promise<{
    data: {
        session: Session;
    };
    error: null;
} | {
    data: {
        session: null;
    };
    error: AuthError;
} | {
    data: {
        session: null;
    };
    error: null;
}>


This is the method signature and it's return type. As you can see the session is inside a data key. You would use it like this:

const {
  data: { session },
} = await supabase.auth.getSession()

if (!session) {
  return NextResponse.redirect(new URL('/login', req.nextUrl));
}
Answer
Right click on my message and you'll find an app to mark it as the solution.
Original message was deleted
As described here
American PipitOP
before I do that
@not-milo.tsx Right click on my message and you'll find an app to mark it as the solution.
American PipitOP
I have one more quick question
    if (req.url.endsWith('/employer') && userDetails?.role_name === 'Candidate') {
        console.log('should redirect to /jobs');
        NextResponse.redirect(new URL('/jobs', req.url));
    }
the log is being logged
but the user is not being redirected, why?
I tried .rewrite() as well
You need to return the response

if (req.url.endsWith('/employer') && userDetails?.role_name === 'Candidate') {
  console.log('should redirect to /jobs');
  return NextResponse.redirect(new URL('/jobs', req.url));
}
American PipitOP
oooh yeah, I feel stupid for asking questions sometimes hahaha
thanks! 😄
marked it, thank you for your help so much 🙂
You're welcome ✨