Next.js Discord

Discord Forum

Issue with @edge-csrf/nextjs csrf library together with API route

Unanswered
LaPerm posted this in #help-forum
Open in Discord
LaPermOP
Hi All, i've got an issue using the mentioned csrf library with API routes - my special use case:

I have a nextjs app, which only destiny is to serve as an API provider

there are multiple other websites (from other domains, apps, etc) not connected and not served from the domain where the API nextjs app is running from, these websites are runned and owned by some customers of mine - i don't have control over them

now i provide the customers with instructions to...

--- include/embed a script tag with an url that calls for one of my api routes

--- include/embed a div tag with a specific ID

if one of these sites get requested from on their customers/users, the above mentioned script will make the api request to my nextjs api server, which in turn returns some self executing function, that will call another api route, which returns some form html (simple name, phone) including a hidden input field, containing a csrf token (generated with another api call like here (row 22-25): https://github.com/kubetail-org/edge-csrf/blob/4334b8e34e504ce2c157cc77050af14254cc1862/examples/next14-approuter-js-submission-static/middleware.ts)

then at the end if some user submits the form, it gets send to another api route to write to db

1 Reply

LaPermOP
PROBLEM:

origin/api/form --> initial request from script tag, passes without any CORS/CSRF issue

origin/api/csrf-token --> second request which is not really an api call, but i just named the route like this, it gets intercepted by the middleware and returns the csrf-token like in the link-example mentioned above

origin/api/form-html --> third request, also passes without issues and returns the form html including the hidden input field and propagates it to the above mentioned div tag

origin/api/form-submission --> fourth request, ends up with 403 "invalid csrf token" like returned in the link-example above, line 14-20 - but only if I request in production mode aka all the request came from another domain, if I try it locally or from a test page within the same domain as the api server itself - the error does not occur, everything works as expected.

So I think the possible issues are:

CORS, CSRF, or maybe the wrong token, i did play so much around with it, that i have lost controll over the correct order, and it seems that every single request generates a new token, so i am not sure. I tried both, creating/requesting the token serverside within the first api route (.../form) and include it inside of the returned self executing function as part of the payload with the next fetch from the client (.../form-html), but I also tried it to just reuest it freshly from the client, before it does the fetch to the .../form-html

Maybe someone could help out...?