Next.js Discord

Discord Forum

Why is my middleware not working?

Answered
American Pipit posted this in #help-forum
Open in Discord
Avatar
American PipitOP
When I'm on the /jobs path, this middleware doesn't return the NextResponse.redirect('/login') and I don't know why. I am not authenticated, and neither does the middleware.ts console.log anything. I've double-checked the paths that I'm matching.

import { NextResponse, type NextRequest } from 'next/server';
import { createClient } from '@/utils/supabase/middleware';
import { redirect } from 'next/navigation';

export async function middleware(request: NextRequest) {
    const { supabase, response } = createClient(request);

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

    if (request.nextUrl.pathname.startsWith('/login') && session) {
        redirect('/');
    }

    if (request.nextUrl.pathname.startsWith('/jobs') && !session) {
        return NextResponse.redirect('/login');
    }

    return response;
}

export const config = {
    matcher: ['/login/:path*', '/jobs/:path*'],
};


This is my project structure:
Image
Answered by vr1
have you tried moving the middleware inside src? I got a warning a few days ago
View full answer

4 Replies

Avatar
vr1
have you tried moving the middleware inside src? I got a warning a few days ago
Answer
Avatar
American PipitOP
yep, that fixed it
thanks for your answer 😦
🙂 *