Next.js Discord

Discord Forum

API call on middleware

Unanswered
Siamese posted this in #help-forum
Open in Discord
SiameseOP
Hi all,
Is this a best practice to make an API call on middleware.ts?
What I want to do is to check from auth0, if the user is sign in, then call the API and retrieve the user information and store into recoil.
import { NextResponse } from "next/server";

export async function middleware(req) {
  const token = req.cookies.get("auth_token")?.value;

  if (!token) {
    return NextResponse.redirect(new URL("/login", req.url));
  }

  try {
    // Fetch user data from an external API
    const res = await fetch("https://api.example.com/auth/validate", {
      headers: { Authorization: `Bearer ${token}` },
    });

    if (!res.ok) {
      return NextResponse.redirect(new URL("/login", req.url));
    }
  } catch (error) {
    console.error("API call failed:", error);
    return NextResponse.redirect(new URL("/error", req.url));
  }

  return NextResponse.next();
}

// Define which paths middleware should run on
export const config = {
  matcher: "/dashboard/:path*",
};

1 Reply