Next.js Discord

Discord Forum

Try to redirect user when is authenticated or unauthenticated using middleware

Unanswered
Savannah posted this in #help-forum
Open in Discord
SavannahOP
Hello, I'm trying to redirect the user depending on whether he's authenticated or unauthenticated, but I must admit I'm a bit lost...

The code ;

middleware.ts :
import {NextRequest, NextResponse} from "next/server";
import {cookies} from "next/headers";
import {decrypt} from "@/app/lib/session";
import createIntlMiddleware from "next-intl/middleware";

const protectedRoutes = ['/dashboard']
const publicRoutes = ['/login', '/register']

export default async function middleware(req: NextRequest) {
    const path = req.nextUrl.pathname;
    const isProtectedRoute = protectedRoutes.includes(path);
    const isPublicRoute = publicRoutes.includes(path);

    const cookie = cookies().get('session')?.value;
    const session = await decrypt(cookie);

    if (isProtectedRoute && !session?.userId) {
        return NextResponse.redirect(new URL('/login', req.nextUrl))
    }

    if (
        isPublicRoute &&
        session?.userId &&
        !req.nextUrl.pathname.startsWith('/dashboard')
    ) {
        return NextResponse.redirect(new URL('/dashboard', req.nextUrl))
    }

    const handleI18nRouting = createIntlMiddleware({
        locales: ['en', 'fr', 'es', 'ar'],
        defaultLocale: 'en'
    });
    const response = handleI18nRouting(req);
    if (response) {
        return response;
    }
    console.log('ababa')
    return NextResponse.next()
}

export const config = {
    matcher : ['/', '/(fr|en|es|ar)/:path*']
}

4 Replies

SavannahOP
(other part of the code, sorry i didn't have a nitro ^^)
session.ts :
import {jwtVerify, SignJWT} from "jose";

const secretKey = process.env.NEXTAUTH_SECRET
const encodedKey = new TextEncoder().encode(secretKey)

export async function encrypt(payload: any) {
    return new SignJWT(payload)
        .setProtectedHeader({alg: 'HS256'})
        .setIssuedAt()
        .setExpirationTime('7d')
        .sign(encodedKey)
}

export async function decrypt(session: string | undefined = '') {
    try {
        const {payload} = await jwtVerify(session, encodedKey, {
            algorithms: ['HS256']
        })
        return payload
    } catch (error) {
        console.log('Failed to verify session')
    }
}
(Btw, it always returning me the console.log('Failed to verify session')
route.ts