Next.js Discord

Discord Forum

middleware ambiguous error

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Avatar
Polar bearOP
this is my middleware.
import { type NextRequest, NextResponse } from 'next/server';
import { validateRequest } from './lib/auth';

export async function middleware(req: NextRequest) {
    const protectedRoutes = ['/dashboard'];
    const currentPath = req.nextUrl.pathname;
    const isProtectedRoute = protectedRoutes.includes(currentPath);

    if (isProtectedRoute) {
        console.log('#'.repeat(30));
        console.log('||It is protected||');
        console.log('#'.repeat(30));
        const { user } = await validateRequest();
        if (!user) {
            return NextResponse.redirect(new URL('/login', req.url));
        }
    }

    return NextResponse.next();
}

export const config = {
    matcher: ['/dashboard'],
    // matcher: ['/((?!api|_next/static|_next/image).*)'],
};

and I get an error when navigating to the dashboard route that says:
TypeError: Cannot read properties of undefined (reading 'reduce')

7 Replies

Avatar
Polar bearOP
I'm using lucia v3
for authentication
Avatar
Polar bearOP
It seems a compatibility issue
Avatar
Polar bearOP
It worked now
import { type NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
const protectedRoutes = ['/dashboard'];
const loginRoutes = ['/login', '/register'];

const verifySession = async (origin: string) => {
    const cookieStore = await cookies();
    const verifyRequest = await fetch(`${origin}/api/auth/verify-session`, {
        headers: { Cookie: cookieStore.toString() },
    });
    const verifySession = (await verifyRequest.json()) as { valid: boolean };

    return verifySession.valid;
};

export async function middleware(req: NextRequest) {
    const currentPath = req.nextUrl.pathname;
    const origin = req.nextUrl.origin;

    const isProtectedRoute = protectedRoutes.includes(currentPath);
    const isLoginRoute = loginRoutes.includes(currentPath);
    if (!isProtectedRoute && !isLoginRoute) {
        return NextResponse.next();
    }

    if (isProtectedRoute) {
        const isValidSession = await verifySession(origin);
        if (!isValidSession) {
            return NextResponse.redirect(new URL('/login', req.url));
        }
    }

    if (isLoginRoute) {
        const isValidSession = await verifySession(origin);
        if (isValidSession) {
            return NextResponse.redirect(new URL('/', req.url));
        }
    }
    return NextResponse.next();
}

export const config = {
    matcher: ['/dashboard', '/login', '/register'],
    // matcher: ['/((?!api|_next/static|_next/image).*)'],
};
api/auth/verify-session/route.ts
// src/app/api/auth/verify-session/route.ts
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';

// here you have to update the import - I'm using a mono repo and the auth stuff is located in a package
import { lucia } from '@/lib/auth';

const handler = async (req: NextRequest) => {
    const sessionId = req.cookies.get(lucia.sessionCookieName)?.value ?? null;

    // no cookie exists
    if (!sessionId) {
        return NextResponse.json({ valid: false });
    }

    const { session } = await lucia.validateSession(sessionId);

    if (!session) {
        return NextResponse.json({ valid: false });
    }

    return NextResponse.json({ valid: true });
};

export { handler as GET };