#Custom header value

1 messages · Page 1 of 1 (latest)

summer bolt
#

I'm using NextJS and the convexAuthNextjsMiddleware. How would I go about assigning a custom header to the returned request, such as 'x-pathname': pathname

main lavaBOT
#

Hi @summer bolt. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To add a custom header to the response in your NextJS application when using convexAuthNextjsMiddleware, you'll need to modify the middleware function to include your custom header.

The convexAuthNextjsMiddleware function accepts a handler function that can return a modified response. You can use this handler to add your custom header to the response.

Here's how you can do it:

import {
  convexAuthNextjsMiddleware,
  createRouteMatcher,
  nextjsMiddlewareRedirect,
} from "@convex-dev/auth/nextjs/server";
import { NextResponse } from "next/server";

export default convexAuthNextjsMiddleware((request, { convexAuth }) => {
  // Your authentication logic here
  
  // Create a response (or use the default one)
  const response = NextResponse.next();
  
  // Add your custom header
  response.headers.set('x-pathname', request.nextUrl.pathname);
  
  return response;
});

export const config = {
  matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};

In this example, I'm creating a new response using NextResponse.next(), which continues the middleware chain with the current request. Then I'm adding a custom header x-pathname with the value of the current pathname from the request URL. Finally, I return the modified response.

This approach works within the context of the convexAuthNextjsMiddleware as shown in the NextJS server authentication documentation.

If you need to combine this with authentication redirects, you can include your conditional logic:

#
export default convexAuthNextjsMiddleware((request, { convexAuth }) => {
  // Authentication redirects if needed
  if (isProtectedRoute(request) && !(await convexAuth.isAuthenticated())) {
    const redirectResponse = nextjsMiddlewareRedirect(request, "/signin");
    redirectResponse.headers.set('x-pathname', request.nextUrl.pathname);
    return redirectResponse;
  }
  
  // For non-redirected requests
  const response = NextResponse.next();
  response.headers.set('x-pathname', request.nextUrl.pathname);
  return response;
});

Remember that any headers you set will be included in the HTTP response sent back to the client.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: