Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS Global Variable with Assignment

I'm new to NextJS, and trying to figure out, how to create a global variable that I could assign a different value anytime. Could someone give a simple example? (I know global might not be the best approach, but still I would like to know how to set up a global variable).

Let's say:

_app.js

NAME = "Ana" // GLOBAL VARIABLE

page_A.js

console.log(NAME) // "Ana"
NAME = "Ben"

page_B.js

console.log(NAME) // "Ben"
like image 548
Isaac Michaan Avatar asked Apr 09 '26 22:04

Isaac Michaan


1 Answers

try using Environment Variables

/next.config.js

module.exports = {
  env: {
    customKey: 'my-value',
  },
}

/pages/page_A.js

function Page() {
  return <h1>The value of customKey is: {process.env.customKey}</h1>
}

export default Page

but you can not change its contents, except by changing it directly in next.config.js

like image 166
Pausi Avatar answered Apr 12 '26 14:04

Pausi