next-csrf icon indicating copy to clipboard operation
next-csrf copied to clipboard

Env variable cant load on browser

Open vedrane opened this issue 4 years ago • 3 comments
trafficstars

As mentioned in #23, environment vars can't load on the browser (obviously). Ok then, how do I SECURELY load the secret for the browser, without exposing it? Is there any way?

vedrane avatar Aug 20 '21 15:08 vedrane

@Get-DevVed-YT the secret shouldn't reach the browser.

We use the secret to generate a token on the server-side. The token then is exposed to the browser by saving it in an httpOnly cookie (can't reach it with JS).

So I think the question is "How do I get the cookie with the token on the browser?" There are two ways:

  • SSR pages. When a user lands on a Next.js SSR page using the middleware it will get the token in a cookie and send it in the subsequent requests.
  • API route. Sending a GET request to an API route using the middleware from the same host will set up the cookie with the token.

j0lvera avatar Aug 26 '21 18:08 j0lvera

So even if the secret is publicly visible, it's fine?

vedrane avatar Aug 27 '21 01:08 vedrane

After much experimentation and help from this excellent community, you cannot leak the secret to the browser. Using NEXT_PUBLIC exposes it in the bundle. @j0lv3r4 is going to take a look into clarifying the documentation but you need to pass the token either via an API call (so the module loads for the request and the cookie gets set)

Or set it up using getServerSideProps which executes only on the server side.

bkotch avatar Sep 22 '21 16:09 bkotch