Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I modify the response in EdgeRouter middleware function? #246

Open
amorey opened this issue Sep 26, 2024 · 0 comments
Open

How can I modify the response in EdgeRouter middleware function? #246

amorey opened this issue Sep 26, 2024 · 0 comments

Comments

@amorey
Copy link

amorey commented Sep 26, 2024

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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant