Reputation: 41
I am trying to store a Sanity token as a secret when deploying my project with Now, but it all doesn't seem to work. Here is my situation:
I added my Sanity token as a secret to the CLI (I called it sanity_token
).
I added a now.json
file in the root of my project:
{
"version": 1,
"build": {
"env": {
"SANITY_TOKEN": "@sanity_token"
}
},
"env": {
"SANITY_TOKEN": "@sanity_token"
}
}```
I used the variable in the sanity.js
as:
...
token: process.env.SANITY_TOKEN,
...
...but it doesn't seem to work neither when running npm run dev
nor when deploying it with now
. The page gets loaded and there are no errors, but I got no content because the Sanity can not be reached. It seems like the secret is missing. What could I be doing wrong?
Upvotes: 2
Views: 565
Reputation: 6509
For this you can use Next's runtime configuration. Since you're dealing with a secret token, you will want to use serverRuntimeConfig
that is only available on the server side:
// next.config.js
module.exports = {
serverRuntimeConfig: {
// either inline or get from env variable
SANITY_TOKEN: process.env.SANITY_TOKEN,
SANITY_TOKEN: "alternatively stored in this file"
}
}
In your server-side coe you can then access SANITY_TOKEN
like this:
// server-side only
import getConfig from "next/config";
const { SANITY_TOKEN } = getConfig().serverRuntimeConfig;
However, this code will crash if you try to run it on the client side, so you'll have to ensure it only runs on the server (see also this issue).
Note that your now.json
file let's you control which env variables are used when deploying to ZEIT Now, but
does not affect your local builds (such as $ npm run dev
and $ npm run build
).
Thus you must set the env variable some other way when running Next locally.
Upvotes: 1