Next.js Discord

Discord Forum

I want to add custom header to all the api calls I make from my next app.

Unanswered
Tropical Kingbird posted this in #help-forum
Open in Discord
Tropical KingbirdOP
I want to attach a header x-uid-jwt to all external API calls made. The value for this header is supposed to be read from a cookie.

I tried implementing this in middleware by checking if the cookie exists. If it doesn't, I set it and also add it to the response as a header. However, it seems that this is not getting triggered when I make any API calls, whether from the client or server. The custom header is not being attached as expected.



import JwtJose from "./app/api/headers/response-with-jwt/jwt-jose";

const enum COOKIE_NAMES {
  GUEST_USER = "fzp-guest-uid",
  USER = "fzp-user-uid",
}
const JWT_SECRET = "somethign";
const JwtAuth = new JwtJose(JWT_SECRET);

export async function middleware(request: NextRequest) {
  const existingUserIdJwt = request.cookies.get(COOKIE_NAMES.USER)?.value ?? "";
  const guestUserIdJwt = request.cookies.get(COOKIE_NAMES.GUEST_USER)?.value ?? "";

  if (await JwtAuth.verifyToken(existingUserIdJwt)) {
    return responseWithJwt(request, existingUserIdJwt, COOKIE_NAMES.USER);
  } else if (await JwtAuth.verifyToken(guestUserIdJwt)) {
    return responseWithJwt(request, guestUserIdJwt, COOKIE_NAMES.GUEST_USER);
  }

  const userId = nanoid();
  const newToken = await JwtAuth.generateToken({ userId });
  return responseWithJwt(request, newToken, COOKIE_NAMES.GUEST_USER);
}

const COOKIE_EXPIRATION = 12 * 2629800000; 

export default function responseWithJwt(request: NextRequest, token: string, cookieName: string) {
  const response = NextResponse.next({
    request: { headers: new Headers(request.headers) },
  });

  response.headers.set(`x-${cookieName}`, token);
  response.cookies.set({
    name: cookieName,
    value: token,
    path: "/",
    sameSite: "lax",
    domain: "example.com",
    httpOnly: false,
    secure: true,
    expires: new Date(new Date().getTime() + COOKIE_EXPIRATION),
  });
  return response;
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

0 Replies