Add helmet to nextjs middleware

96 Views Asked by At

I have a full-stack nextjs application and I want to add helmet for having secure headers. I try to use 'next-connect' package but helmet won't add new headers to response headers. (I am using nextjs13 with 'pages' routes) middleware.ts:

import {
  NextResponse,
  type NextRequest,
  type NextFetchEvent,
} from "next/server";
import { createEdgeRouter } from "next-connect";
import helmet from "helmet";
const router = createEdgeRouter<NextRequest, NextFetchEvent>();
router.use(async (req, event, next) => {
  helmet(); //will not add any new header to response 
  return next();
});
router.all(() => {
  // default if none of the above matches
  return NextResponse.next(); //continue to next middleware
});
export function middleware(req: NextRequest, event: NextFetchEvent) {
  return router.run(req, event);
}
export const config = {
  matcher: "/api/:path*", //apply this middleware to /api routes
};
1

There are 1 best solutions below

0
Evan Hahn On

Try using next-connect's Express wrapper.

router.use(expressWrapper(helmet()));