How to intercept every server components response
Unanswered
Irish Red and White Setter posted this in #help-forum
Irish Red and White SetterOP
Hello, how can one intercept all the server components response especially when checking for expired token with the intent to refresh it and retry the requests?
I tried using middleware but do not know how to get the response from server.
I tried using middleware but do not know how to get the response from server.
2 Replies
Taigan
Mind sharing some code on what you've tried'
Irish Red and White SetterOP
Hi @Taigan
I missed your reply.
I honestly lack a clue on how to do it. Since every requests passes through a middleware, I thought it an ideal place to handle it. But with NextJs, I don't know how to do.
The intent here is to refresh the token once it expires
I missed your reply.
import { NextRequest, NextResponse } from "next/server";
const baseUrl = process.env.NEXT_PUBLIC_API_URL;
export default async function middleware(req) {
...
if (pathName.pathname.startsWith('/dashboard')) {
const newResponse = NextResponse.rewrite(new URL(req.url, req.url), {
})
if (newResponse.status === 401) {
const url = req.nextUrl.clone();
url.pathname = "/authentication/sign-in";
return NextResponse.redirect(url);
}
if (!authToken) {
if (!refreshToken) {
return NextResponse.redirect("http://localhost:3000/authentication/login");
}
const response = await api.refreshUserToken();
const data = await response.json();
const nextResponse = NextResponse.next();
if (!data.ok) {
return NextResponse.redirect("/authentication/login");
}
nextResponse.cookies.set({
name: 'token',
value: data.token,
httpOnly: true,
})
return NextResponse.next();
}
const requestHeaders = new Headers(req.headers);
const response = NextResponse.rewrite(new URL(req.url), {
request: {
headers: requestHeaders,
}
});
return NextResponse.next();
}
}
export const config = {
matcher: [
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
"/(api|trpc)(.*)",
],
};
I honestly lack a clue on how to do it. Since every requests passes through a middleware, I thought it an ideal place to handle it. But with NextJs, I don't know how to do.
The intent here is to refresh the token once it expires