Hopefully this is obvious but I'm doing a redesign, more just a tidying up, but whatever. Sorry for the appearance

Fitzsimons.devThoughtsTipsSite Reviews

Enviromental variables in Serverless-Stack and NextJs

How to pass around ENV variables in SST and NextJs

I've been learning NextJs and Serverless Stack. This stack seems ideal for my goals on the front and back ends. This post is mostly for me to cement how process.env works in this stack so I fully understand it. When you create a site stack using sst you'll have a stack file that has something like this.

// Create a Next.js site
this.site = new sst.NextjsSite(this, 'Site', {
path: 'frontend',
environment: {
// Pass the table details to our app
FROM_SST: 'Hello World',
},
});

You'll run your stack with npx sst start and start your app with npm run dev (which should be calling "sst-env -- next dev") in your package json. In your _app.js add in the following console.log.

function MyApp({ Component, pageProps }) {
console.log("process.env.FROM_SST: ", process.env.FROM_SST);

You get two console.logs here, one, in the terminal that's running the next app and the other at localhost. In localhost you'll see the log output but in the application, you'll only see the string output, but the value from FROM_SST will be undefined. This massively tripped me up. Inside next.config.js add in the following:

env: {
FROM_NEXT_ENV: process.env.FROM_SST,
}

and update that console.log from earlier in _app.js to the following:

function MyApp({ Component, pageProps }) {
console.log("process.env.FROM_SST: ", process.env.FROM_SST);
console.log("process.env.FROM_NEXT_ENV: ", process.env.FROM_NEXT_ENV);

You'll have to restart your terminal, but, the terminal running NextJs should have both environmental variables printing out, and the console in localhost will have the SST environmental variable as undefined and the FROM_NEXT_ENV as "Hello World". I spent an absurd amount of time fumbling around with this but happily I've got it all wired up correctly now!