API call on middleware
Unanswered
Siamese posted this in #help-forum
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
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
@Siamese 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`.
ts
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*",
};
Well, I am not sure if it's correct to say it's a bad practice but I feel like most auth libraries have middleware which we can wrap our middleware by it.
if they don't provide, I think rather than making an API request in the middleware, it's better to have that logic in other util and wrap your api route or pages again.
It's just my opinion
if they don't provide, I think rather than making an API request in the middleware, it's better to have that logic in other util and wrap your api route or pages again.
It's just my opinion