I am using Nextjs version 14 and I have placed the Middleware file inside src folder. I also use NextAuth for authorization, which works properly. But when I want to modify the headers inside middleware file(to run on the client server side), nothing changes and the changed headers is not taken on the backend side. However, if I put the changed headers value inside Fetch, it will be received on the backend side, but it couldn’t be rendered statically because it used headers.
import NextAuth from "next-auth";
import { authConfig } from "../auth.config";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "./helper/authentication";
export default NextAuth(authConfig).auth;
export const config = {
// https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};
const bypassAuth = ["/login", "/register"];
export async function middleware(request: NextRequest) {
if (!bypassAuth.includes(request.nextUrl.pathname)) {
const username: string | null | undefined = await getToken();
if (!username) {
return NextResponse.redirect(new URL("/login", request.url));
}
const requestHeaders = new Headers(request.headers);
requestHeaders.set("Authorization", username);
requestHeaders.set("Content-Type", username);
const response = NextResponse.next();
response.headers.set("Authorization", username);
response.headers.set("xxx", "123");
response.headers.append("Authorization", username);
return response;
}
return NextResponse.next();
}
and when using customFetch for all services and losing static rendering
import { auth } from "../../auth";
async function getToken() {
const session = await auth();
const username = session?.user?.name;
return username;
}
export const customFetch = async (url: any, options?: any) => {
const controller = new AbortController();
const { signal } = controller;
let username: string | null | undefined = await getToken();
const headers = {
"Content-Type": "application/json",
// Add any other headers you want to include in every fetch call
Authorization: username,
};
const response = await fetch(url, {
...options,
signal,
headers: {
...headers,
...options?.headers,
},
});
return response;
};