Next.js Discord

Discord Forum

Why I can't use status code from fetch event in next js to determine NextResponse

Answered
Tan posted this in #help-forum
Open in Discord
TanOP
Here is my code. I am trying to verify token from middleware. There is a different server running for auth verification. I have used this :
import { NextResponse } from "next/server";
import type { NextFetchEvent, NextRequest } from "next/server";
import { BACKEND_URL } from "./app/constant";

export function middleware(req: NextRequest, event: NextFetchEvent) {
  event.waitUntil(
    fetch(`${BACKEND_URL}/verify`, {
      headers: { "Content-Type": "application/json" },
      method: "POST",
      body: JSON.stringify({ token: req.cookies.get("token")?.value }),
    }).then((res) => {
      if (res.status === 200) {
        return NextResponse.next();
      } else {
        return NextResponse.redirect("http://locahost:3000");
      }
    }),
  );
}

export const config = {
  matcher: "/dashboard",
};

But even the response is not 200 it is still rendering dashboard.
Answered by Ray
waitUntil is useful for the background task. In your case, you shouldn't need it
View full answer

6 Replies

Answer
@Ray `waitUntil` is useful for the background task. In your case, you shouldn't need it
TanOP
What would be the best approach for security if I have a seperate backend 🤔
to secure client side
@Tan What would be the best approach for security if I have a seperate backend 🤔
export function middleware(req: NextRequest, event: NextFetchEvent) {

  await fetch(`${BACKEND_URL}/verify`, {
      headers: { "Content-Type": "application/json" },
      method: "POST",
      body: JSON.stringify({ token: req.cookies.get("token")?.value }),
    }).then((res) => {
      if (res.status === 200) {
        return NextResponse.next();
      } else {
        return NextResponse.redirect("http://locahost:3000");
      }
    })

}
just use middleware without waitUntil