kubetail-org / edge-csrf

CSRF protection library for JavaScript that runs on the edge runtime (with Next.js, SvelteKit, Express, Node-HTTP integrations)
MIT License
146 stars 9 forks source link

CSRF on App not working #12

Closed kjavier closed 1 year ago

kjavier commented 1 year ago

headers() only provides read-only request data and not from response data.

CSRF is attached to response headers.

Are you able to successfully get any csrf data from any server components in the app directory just by using headers()?

amorey commented 1 year ago

Using headers() to retrieve the response header set by edge-csrf is working in the example here: https://github.com/amorey/edge-csrf/tree/main/example-ts-appdir

I just tried it with the latest version of Next.js (13.4.16) and it also worked.

Do you have an example of it not working with the app router?

kjavier commented 1 year ago

I have multiple chained middlewares. I notice that you require NextResponse as a parameter. Can it be that it would be flexible to accept even NextMiddleware, ex: next(request, nextFetchEvent) instead of NextResponse.next() ? I can see the csrf token in the response header on the browser but cannot see it when I do headers() on server components.

export default function createCSRF(next: NextMiddleware) {
  return async (request: NextRequest, nextFetchEvent: NextFetchEvent) => {
    const response = await next(request, nextFetchEvent);

    if (response) {
       const csrfError = await csrf_protect(request, response);
    }
  }
}

Update: I cloned the nextMiddleware response into NextResponse object but I cant still see the csrf-token when I do headers().

kjavier commented 1 year ago

I figured that the bug that I am getting is not edge-csrf's fault but that of another library.

amorey commented 1 year ago

Ok, thanks for the update. Happy to hear the issue wasn't with edge-csrf.