0
0
NextJSframework~30 mins

Environment variables in production in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Environment variables in production
📖 Scenario: You are building a Next.js app that needs to use API keys safely in production. Environment variables help keep API keys out of your source code.
🎯 Goal: Create a Next.js app that reads an API key from environment variables and displays a message using that key on the homepage.
📋 What You'll Learn
Create a file to hold environment variables
Add a variable for the API key
Access the environment variable in a Next.js page
Display the API key value on the homepage
💡 Why This Matters
🌍 Real World
Many web apps need to configure API keys without hardcoding them in the code. Environment variables let you do this securely in production.
💼 Career
Understanding environment variables is essential for deploying real-world Next.js apps and working with cloud platforms or CI/CD pipelines.
Progress0 / 4 steps
1
Create the environment variable file
Create a file named .env.production in the root of your Next.js project. Inside it, add the line NEXT_PUBLIC_API_KEY=prod_key_123 exactly as shown.
NextJS
Need a hint?

This file stores environment variables for production. The variable name must start with NEXT_PUBLIC_ to be accessible in the browser.

2
Create the Next.js page to use the variable
In the app/page.tsx file, create a React functional component named Page. Inside it, create a constant apiKey that reads the environment variable process.env.NEXT_PUBLIC_API_KEY.
NextJS
Need a hint?

Use const apiKey = process.env.NEXT_PUBLIC_API_KEY; inside the component to access the variable.

3
Display the API key on the homepage
Inside the Page component, return a <main> element containing a <p> tag that shows the text "The API key is: " followed by the apiKey value.
NextJS
Need a hint?

Use JSX to return the main and paragraph elements with the API key inside curly braces.

4
Add metadata for accessibility and SEO
Add a metadata export in app/page.tsx with a title set to 'API Key Display' and a description set to 'Shows the API key from environment variables.'.
NextJS
Need a hint?

Export a constant named metadata with the required title and description fields.