NextJS Global Variable with Assignment

Viewed 6887

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"
3 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

Nextjs no special ways to provide global variables you want. You can achieve by:

  1. Stateful management tool, like redux-react
  2. Using Context

It's not like it's impossible, I created a file called _customGlobals.jsx and put this as content

String.prototype.title = function () {
  const sliced = this.slice(1);
  return (
    this.charAt(0).toUpperCase() +
    (sliced.toUpperCase() === sliced ? sliced.toLowerCase() : sliced)
  );
};

and imported it in _app.jsx like this:

import "./_customGlobals";

So now I can call this function on any string anywhere in my project like this: "this is a title".title()

Related