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

Storing in react-context? #13

Open
mosnicholas opened this issue Sep 18, 2023 · 1 comment
Open

Storing in react-context? #13

mosnicholas opened this issue Sep 18, 2023 · 1 comment

Comments

@mosnicholas
Copy link

mosnicholas commented Sep 18, 2023

This package is super helpful, thank you.

Do you by any chance have any opinions / ideas on storing the csrf token in react context? I'd like to do this for 2 reasons:

  1. Instead of having to pass it around subcomponents, I can pull it out of react context.
  2. I'm using react-query to make my API requests and often they are simply JSON requests. Ideally, I would just use the header defined approach to avoid having to pass it in as a key and polluting my API request body. Having it in the context would aid with that.

Does this present any security concerns?

@mosnicholas mosnicholas changed the title HOC for page wrapper? Storing in react-context? Sep 18, 2023
@amorey
Copy link
Member

amorey commented Oct 31, 2023

Happy to hear you're finding edge-csrf useful! Apologies for the late reply.

It's definitely possible to use React context to share the CSRF token but it would have some drawbacks, namely, if you fetch the token asynchronously (e.g. inside an useEffect() hook) then your code will still have to handle the case where the token isn't available yet. Alternatively you can create a library function that fetches the CSRF token synchronously and provides it to your code on an as-needed basis. You can cache the token for follow-on requests and further optimize the function by pre-fetching the token on page load or providing it in the initial html depending on your needs. Here are some examples you can use as a guide:
https://github.com/amorey/edge-csrf/tree/next14/examples/next13-approuter-js-submission-static
https://github.com/amorey/edge-csrf/tree/next14/examples/next13-approuter-js-submission-dynamic

I've been thinking about how to add a method to the core library to do this and so far I can't come up with a developer-friendly yet performant way to do it. "Partial Prerendering" in Next.js 14 might be a good way to do it but I'm not sure yet.

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

2 participants