Search code examples
next.jsstoryblok

Hiding Storyblok API-Key


I'm using Next.js with Storyblok and recently made use of the react-next-boilerplate.

I noticed that they put the preview token in the _app.js, so essentially publish it:

storyblokInit({
  accessToken: "your-preview-token",
  use: [apiPlugin],
  components,
});

If I use an environment variable instead, which isn't available on the client, I get the error

You need to provide an access token to interact with Storyblok API

in the client. That's because (I think) my components use StoryblokComponent, which makes use of the global Storyblok state. So I wonder:

  • Should I ignore this error, as I don't plan to interact with the Storyblok API other than using it for component rendering (all the data comes from the server, as far as I understand the concept of static site generation), and component rendering seems to be still working?

  • Should I just publish the preview token?

  • Should I create two tokens, one for the server and one for the client?

  • Setting the token to process.env.STORYBLOK_API_KEY || "NULL" (where "NULL" can be anything except the empty string) also works (no more errors) but seems like a weird solution.

I don't really understand why they combine these two things, component rendering and data fetching, in the same function.


Solution

  • I would use a .env.local file and populate it with:

    STORYBLOK_API_KEY=your-preview-token
    

    To use the environment variable inside _app.js you have to pass it to next.config.js like this:

        module.exports = {
          env: {
            STORYBLOK_API_KEY: process.env.STORYBLOK_API_KEY,
          }
        }
    

    Source: https://nextjs.org/docs/basic-features/environment-variables