The way to use surroundings variables in Subsequent.js (features a working instance app) | Digital Noch

The way to use surroundings variables in Subsequent.js (features a working instance app) | Digital Noch

Subsequent.js is a React framework that makes constructing quick, user-friendly web sites straightforward. It makes use of server-side rendering to pre-render pages on the server, which makes them load sooner for customers. Atmosphere variables are a method to retailer delicate data, akin to passwords or API keys, exterior of your code. This makes it safer, it is without doubt one of the tenants of the 12-factor app. On this publish, you’ll discover ways to correctly use surroundings variables on each the server and consumer aspect of Subsequent.js. Let’s get began!

Desk of contents #

Recognition of Subsequent.js #

Subsequent.js is a quick, scalable, and easy-to-use React framework that can be utilized to construct static, dynamic, and server-side rendered purposes. It’s in style for its static website technology, server-side rendering, routing, pre-rendering, and web optimization options. A few of its rivals are Nuxt.js, Gatsby, and Remix.
Subsequent.js is the most well-liked React.js meta framework for those who have a look at the search tendencies on Google for the final 5 years.

Next.js is the most popular React meta framwork

Subsequent, you’ll study surroundings variables and their use in net purposes.

Atmosphere variables #

Atmosphere variables are a set of variables which can be used to retailer details about the surroundings wherein an online software is operating. They’re outlined in a key and worth pair. This data can embrace issues like the trail to the applying’s information, the title of the database, and the port quantity that the applying is listening on.

Atmosphere variables are sometimes used to configure purposes, and so they may also be used to retailer information that must be accessed by a number of components of an software.

Atmosphere variables is usually a highly effective instrument for configuring and managing net purposes. By understanding how they work, you should utilize them to make your purposes extra versatile and simpler to keep up. For instance, beneath is a pattern .env file used for an software’s surroundings variables:


With the above surroundings variables in a .env file or as working system-level surroundings variables, you may select the database you need. As an example, on staging it would level to a staging database and for a manufacturing surroundings, the manufacturing database credentials will probably be used.
Yet another factor to note above is the DB_URL which is constructed by referencing the opposite variables with a $ signal.

Subsequent.js will routinely broaden the variables utilizing $ to reference different variables, so it would assemble a sound DB_URL changing the precise surroundings variables.
Within the subsequent part, you’ll study Subsequent.js surroundings variables.

Atmosphere variables in Subsequent.js #

For this publish, you’ll use Subsequent.js 13 with the app router (not the pages folder). To make use of surroundings variables in Subsequent.js, you may create a .env.native file in your undertaking’s root listing. This file will include your entire surroundings variables, which you’ll then entry in your code utilizing the method.env object whereas doing backend execution or server-side parts.
For instance, when you have an surroundings variable referred to as SECRET_KEY, you may entry it in your code like this:

const secretKey = course of.env.SECRET_KEY;

You may as well use surroundings variables to arrange completely different configurations to your web site. For instance, you possibly can create an surroundings variable referred to as PRODUCTION that you simply set to true when your web site is reside. This might mean you can use completely different settings to your manufacturing web site than you’d to your growth web site. You may learn extra about this within the official docs.

Subsequent.js browser stage surroundings variables #

At occasions you have to to show some variables to be accessible on the frontend on the browser stage. After all, these variables can’t be secret (like a password) as they are often learn by everybody as it’s a part of the frontend code.

Let’s say if you wish to use Google Analytics 4 then you have to to show the GA4 measurement ID to the browser.
To show a public surroundings variable in Subsequent.js you must prefix the surroundings variable with NEXT_PUBLIC, so for the GA4 measurement ID it may be uncovered as follows:


You’ll know concerning the load order for surroundings variables in Subsequent.js within the subsequent part.

Atmosphere variable load order in Subsequent.js #

The surroundings variables have a priority order in Subsequent.js which is as beneath:

  1. course of.env
  2. .env.$(NODE_ENV).native
  3. .env.native (Not checked when NODE_ENV is check.)
  4. .env.$(NODE_ENV)
  5. .env

For NODE_ENV the one allowed values are growth, manufacturing, and check. In case of the priority, if NODE_ENV is growth and also you outline a variable say DB_HOST in each .env.growth.native and .env, the worth in .env.growth.native will probably be used as per above precedence order.
You’ve got realized about Subsequent.js surroundings variables, now it’s time to the information into observe within the following part with an instance app.

Instance metropolis climate app #

To place the issues you’ve got realized about Subsequent.js surroundings variables you’ll clone and run an instance app that may present the temperature of a given metropolis. The applying has two components. The primary half to name an API with an API key to get the climate for a metropolis will use a server-only surroundings variable.

Then the second half is including Google Analytics 4 script to the applying which can use the general public (frontend/browser) stage surroundings variable.
The operating app appears to be like just like the beneath:

Next.js city weather app running on Vercel

As you may see, it’s a inventory Subsequent.js app put in with npx create-next-app@newest. It doesn’t use Typescript and Tailwind nevertheless it does use the brand new app router and EsLint. To return to the above stage, the next two Subsequent.js surroundings variables have been used:


You may perceive what is occurring within the software by taking a look on the visible illustration of the communication movement between the methods concerned as follows:

Next.js city weather app talking with API Ninjas API and Google Analytics

When the consumer hits the URL with (or with out the town), the Subsequent.js app will ship a request to API Ninjas with the API key supplied (free of charge) by API Ninjas. This app calls the API Ninjas’ climate API sending the town title. If no metropolis title is given it falls again to London.

Should you put the API Key from API Ninjas in public different folks can use it and/or abuse it as properly. That’s the reason it’s set as a server-level Subsequent.js surroundings variable. In your app to work additionally, you will have to register and get your individual free API key from API Ninjas.

One other system concerned is Google Analytics. A GA4 tag is added to the climate app that can report the web page views to Google Analytics. It used the measurement ID to determine the app. You may comply with this tutorial to get a step-by-step course of so as to add GA4 on a Subsequent.js app.

The aim of this information is to clarify the Subsequent.js surroundings variables. Because the GA4 script runs on the browser stage the measurement id surroundings variable is about to NEXT_PUBLIC in order that it may be used on the frontend/browser. This surroundings variable may be uncovered to the general public.

The app is deployed on Vercel at the moment, you can even use Subsequent.js with Docker to run the app domestically. With Docker, you may simply run any Subsequent.js software with out the necessity to have a specified model of Node.js or NPM. These dependencies may be configured as code within the Dockerfile.

Metropolis climate Subsequent.js app code #

The code of the inventory Subsequent.js starter template has been modified a bit so as to add a server name to API Ninjas and likewise add the Google Analytics 4 script on the web page. You’ll need to understand how Subsequent.js works as a prerequisite. All of the code modifications have been carried out to the src/app/web page.js file which appears to be like just like the beneath:

import Picture from 'subsequent/picture';
import types from './web page.module.css';
import Script from 'subsequent/script';

async operate getWeatherData(metropolis)
const res = await fetch(`$metropolis`,
'Content material-Sort': 'software/json',
'X-API-Key': course of.env.API_NINJAS_API_KEY,
const information = await res.json();
information.metropolis = metropolis;

return information;

export default async operate Dwelling(req)

The change to this src/app/web page.js are as follows:

  • The Script tag has been imported from subsequent/script on line no 3
  • On the road 4, You’ve got additionally assigned the Subsequent.js surroundings variable NEXT_PUBLIC_GA_MEASUREMENT_ID to a relentless referred to as GA_MEASUREMENT_ID
  • From traces 6-17, the getWeatherData async operate makes use of fetch to name the API Ninjas’ climate API passing the town that’s handed in as a parameter to the operate. It returns the info obtained from the API name after including the town to it. This operate runs on the server and it used the API_NINJAS_API_KEY Subsequent.js surroundings variable to make the decision to the API.
  • Within the Dwelling element, metropolis is fetched from the URL question parameter if it exists else the town variable will get a fallback worth of London on line 20.
  • On line 21, the getWeatherData operate is known as with the town fixed set on line 20.
  • The title of the town and the present temperature in that metropolis are rendered, on traces 24-28
  • On traces 60-71, the GA4 tag is positioned which makes use of the general public Subsequent.js surroundings variable twice. As soon as for the Google tag supervisor and once more at line 69 for the GA config.

With these modifications now you’ve got used each the server aspect and consumer (browser) aspect Subsequent.js surroundings variable in a small however helpful and dealing software. All of the code is offered within the public GitHub repository.

You may simply deploy this app on Vercel by clicking the “Deploy” button on the readme or discover it operating on Vercel. You may clone/fork the repo and alter the to suit your wants.

Hurray! You’ve got realized find out how to use the Subsequent.js surroundings variable with the assistance of an instance working app that fetches the reside climate for any given metropolis and sends again analytics to GA 4.

Conclusion #

On this information, you realized about Subsequent.js and its reputation. You then additionally gained some information about surroundings variables for net purposes and particularly for Subsequent.js. After that, you realized each sorts of Subsequent.js surroundings variables (server and consumer ones that are public) and the order of priority to make use of them.

You then checked out an instance of a Subsequent.js app that pulls within the present climate for any given metropolis utilizing each server-level and consumer/browser-level surroundings variables.

I hope you realized one thing new, preserve absorbing extra information. When you’ve got any questions or feedback please depart them beneath.

#surroundings #variables #Subsequent.js #contains #working #app

Related articles


Leave a reply

Please enter your comment!
Please enter your name here