Next.js Discord

Discord Forum

Cookie doesn't include when the current path is from the api route

Unanswered
Bigheaded ant posted this in #help-forum
Open in Discord
Bigheaded antOP
Hello everyone, is there anyone knows how we can get the cookie when the path of url accessed the api route. So I have a case, I've already set the cookie after user logged in, and then I check this cookie in the middleware, when it comes to url /api or api routes, this cookie data is null.

This is my code in the middleware.ts

export async function authMiddleware(request: NextRequest) {
    const { pathname } = request.nextUrl;

    // Fetch user data and token from cookies
    const userCookie = await getCookies("__u__");
    const tokenCookie = await getCookies("__tk__");

    // Redirect ke login jika user mencoba akses dashboard tanpa autentikasi
    if (pathname.startsWith("/dashboard") && (!userCookie || !tokenCookie)) {
        toast({
            title: "Akses ditolak",
            description: "Harap login terlebih dahulu",
            variant: "destructive",
        });
        return NextResponse.redirect(new URL('/auth/login', request.url));
    }

    // Redirect ke dashboard jika user sudah login dan mencoba mengakses halaman login/register
    if ((pathname.startsWith("/auth/login") || pathname.startsWith("/auth/register")) 
        && userCookie && tokenCookie) {
        return NextResponse.redirect(new URL('/dashboard', request.url));
    }

    console.log(pathname, userCookie, tokenCookie) // Both of userCookie and tokenCookie are empty
    if (pathname.startsWith("/api") && (!userCookie || !tokenCookie)) {
        return NextResponse.json(
            { message: "Unauthorized" },
            { status: 401 } // Kirim response error 401 Unauthorized
        );
    }

    return NextResponse.next();
}

2 Replies

Bigheaded antOP
Uppp
Bigheaded antOP
Uppp