I’m trying to use different environment variables depending on the deployment context. The idea is to use a branch, “qa”, to do pre-deployment testing and then use “main” for production. I’m working with next.js.
My netlify.toml looks like this:
[build]
command = "next build"
functions = "netlify/functions"
publish = "out"
[context.production]
[context.branch-deploy]
[context.qa.environment]
MY_SPECIAL_VAR = "something goes here"
I then have a basic Next page that uses getServerSide props, where I’m checking that the environment variable is being loaded properly.
import Head from 'next/head';
import Header from '../components/layout/Header';
import styles from '../styles/Home.module.css';
export default function Home({ thing }) {
return (
<div className={styles.container}>
<Head>
<title>Nextjs | Next-Auth</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<main className={styles.main}>
<h1 className={styles.title}>
The thing is {thing}
Authentication in Next.js app using Next-Auth
</h1>
</main>
</div>
);
}
export function getServerSideProps(ctx) {
return {
props: {
thing: process.env.MY_SPECIAL_VAR
}
};
}
When I do this locally everything works, but when I push to my qa branch and there is an automatic build, MY_SPECIAL_VAR is undefined (or at least doesn’t show up).
Is this because the variable is not available during runtime and only at build time? (I don’t think that’s the case). Or is my .toml syntax wrong? I’ve tried to follow the docs on this but weirdly can’t get it to work.
Additionally, what is the best approach to define the context where the build is happening? I tried to set NODE_ENV but there was a bit of output in the build logs that said this was a bad idea.
It would be great to have some feedback on why this isn’t working, how I can validate my env variables and what the best approach is to set different environment variables for different build contexts. Thanks in advance for your help .