next-csrf: "TypeError: Secret string must be provided."

I get this error when trying to use next-csrf while using the documentation 1:1. It thinks the CSRF_SECRET is empty, even though it is set in .env.

It works when I prepend “NEXT_PUBLIC_” to the env variable but this would expose the secret to the browser: https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser (and I can also see this in the source code)

This is my csrf.js:

// file: lib/csrf.js
import { nextCsrf } from "next-csrf";

const options = {
    secret: process.env.CSRF_SECRET
}

export const { csrf, csrfToken } = nextCsrf(options);

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 7
  • Comments: 21 (6 by maintainers)

Most upvoted comments

Also, I found a way use the existing documentation to load the getServerSide props without any api calls. The answer is ES2020’s dynamic imports.

export async function getServerSideProps() {
    const { csrfToken } = await import("../lib/csrf");
    return {
        props: { csrfToken: csrfToken },
    };
}

Also, as I was verifying the lack of leaking secrets, someone over at React has a similar concern.

image

@Brawl345, I got a similar error but I fix with this

image

Okay, there are two things:

  • The documentation explains the implementation wrong. The csrfToken shouldn’t be set up in a custom _app.js because it runs on both the client and server AND generates the token only on the server.
  • The csrfToken should be set up on an SSR login page.

I’m preparing a pull request to clarify the points above and set up an example/ folder with the right implementation.

This got fixed in the last release. Thanks for the info all!

Tried with .env.local and got the same error.