hoangvvo/next-connect

How can I modify the response in EdgeRouter middleware function?

Opened this issue · 0 comments

Hi,

I'm trying to integrate Edge-CSRF with next-connect (into a Next.js 14 app using app router) and in order to do so I need to access the response object from inside an edge router .use() function. What is the recommended way to modify the response from inside router.use()?

I want to be able to do something like this but it doesn't work because the response object isn't being passed between the middleware functions:

import { createCsrfProtect, CsrfError } from '@edge-csrf/nextjs';
import { NextResponse } from 'next/server';
import type { NextFetchEvent, NextRequest } from 'next/server';
import { createEdgeRouter } from 'next-connect';

const csrfProtect = createCsrfProtect({
  cookie: {
    secure: process.env.NODE_ENV === 'production',
  },
});

const router = createEdgeRouter<NextRequest, NextFetchEvent>();

// Execute middleware before csrf protection

router.use(async (request, event, next) => {
  const response = NextResponse.next();
  response.headers.set('X-BEFORE', new Date().toISOString())
  return next();
});

// Apply csrf protection

router.use(async (request, event, next) => {
  const response = NextResponse.next();

  try {
    await csrfProtect(request, response);
  } catch (err) {
    if (err instanceof CsrfError) return new NextResponse('invalid csrf token', { status: 403 });
    throw err;
  }

  return next();
});

// Execute middleware after csrf protection

router.use(async (request, event, next) => {
  const response = NextResponse.next();
  response.headers.set('X-After', new Date().toISOString())
  return next();
});

// Define router fallback and export middlware function

router.all(() => {
  return NextResponse.next();
});

export function middleware(request: NextRequest, event: NextFetchEvent) {
  return router.run(request, event);
}