Next.js Discord

Discord Forum

My API endpoint is getting redirected to the homepage

Answered
Elm sawfly posted this in #help-forum
Open in Discord
Elm sawflyOP
My API endpoint is getting redirected to the homepage|

import { NextRequest, NextResponse } from 'next/server'
import { jwtVerify } from 'jose'

// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
    const token = request.cookies.get("token")?.value;
    const secret = new TextEncoder().encode(process.env.JWT_SECRET);

    if (!token) {
        return NextResponse.json({
            message: "Unauthorized! Login needed",
            success: false
        }, { status: 401 })
    }

    try {
        const verifyToken = await jwtVerify(token, secret);

        if (verifyToken) return NextResponse.redirect(new URL("/"));
        return NextResponse.next();

    } catch (err) {
        console.log(err);
        return NextResponse.json({
            message: "Middleware error",
            err
        })
    }
};

export const config = {
    matcher: ["/api/expenses", "/api/passwords"]
};


I hope my folder structure is right

18 Replies

aren't you telling it do so?
@@ts-ignore aren't you telling it do so?
Elm sawflyOP
import { NextRequest, NextResponse } from 'next/server'
import { jwtVerify } from 'jose'

// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
    const token = request.cookies.get("token")?.value;
    const secret = new TextEncoder().encode(process.env.JWT_SECRET);

    if (!token) {
        return NextResponse.json({
            message: "Unauthorized! Login needed",
            success: false
        }, { status: 401 })
    }

    try {
        const verifyToken = await jwtVerify(token, secret);

        if (verifyToken) return NextResponse.redirect(new URL("/", request.url));
        return NextResponse.next();

    } catch (err) {
        console.log(err);
        return NextResponse.json({
            message: "Middleware error",
            err
        })
    }
};

export const config = {
    matcher: ["/api/expenses", "/api/passwords"]
};
Changed to request.url
but same result
Any solution for this?
Elm sawflyOP
Ok ya
@@ts-ignore you're redirecting the request to `/`
Elm sawflyOP
When i try to access the token by using
token._id
it gives me undefined
and when i log the token, it logs the token
how to access the id?
what is your code for setting the token? (edit, that shouldn't actually change anything)
@riský what is your code for setting the token? (edit, that shouldn't actually change anything)
Elm sawflyOP
import { NextResponse } from "next/server";
import { getXataClient } from "@/src/xata";
import { SignJWT } from 'jose'


export async function POST(req: Request) {

    const xata = getXataClient();
    const { email } = await req.json();

    try {
        const registeredUser = await xata.db.Users.filter({ email }).getFirst();
        if (!registeredUser) return NextResponse.json({ message: "User Not Registered!" }, { status: 401 });

        const token = await new SignJWT({ _id: registeredUser.id })
            .setProtectedHeader({ alg: "HS256" })
            .setIssuedAt()
            .setExpirationTime("2h")
            .sign(new TextEncoder().encode(process.env.JWT_SECRET));

        const response = NextResponse.json({
            message: "Login was Successful!",
            token
        }, { status: 201 });

        response.cookies.set("token", token);
        return response;

    } catch (error: any) {
        console.log(error);
        return NextResponse.json({
            message: error
        }, { status: 400 });
    };
};
hmm looks good
Answer
Elm sawflyOP
Ok
yeah, i looked over that you were just verifying it, and not decoding it, glad to see it worked 🎉