0
0
NextJSframework~10 mins

Environment variables in production in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to access an environment variable in a Next.js component.

NextJS
const apiUrl = process.env.[1];
Drag options to blanks, or click blank then click option'
APUBLIC_API_URL
BAPI_URL
CNEXT_PUBLIC_API_URL
DNEXT_API_URL
Attempts:
3 left
💡 Hint
Common Mistakes
Using environment variables without the NEXT_PUBLIC_ prefix for client-side code.
Trying to access server-only variables in the browser.
2fill in blank
medium

Complete the code to load environment variables from a .env file in Next.js.

NextJS
export default function handler(req, res) {
  const secret = process.env.[1];
  res.status(200).json({ secret });
}
Drag options to blanks, or click blank then click option'
ANEXT_PUBLIC_SECRET
BSECRET_KEY
CNEXT_SECRET_KEY
DSECRET
Attempts:
3 left
💡 Hint
Common Mistakes
Using NEXT_PUBLIC_ prefix for server-only variables.
Not importing dotenv/config when needed in custom server code.
3fill in blank
hard

Fix the error in the code to correctly use environment variables in Next.js API route.

NextJS
export default function handler(req, res) {
  const dbPassword = process.env.[1];
  res.status(200).json({ dbPassword });
}
Drag options to blanks, or click blank then click option'
ANEXT_PUBLIC_DB_PASSWORD
BDB_PASSWORD
CPUBLIC_DB_PASSWORD
DDATABASE_PASSWORD
Attempts:
3 left
💡 Hint
Common Mistakes
Using NEXT_PUBLIC_ prefix for server-only environment variables.
Trying to access variables that are not defined in .env.
4fill in blank
hard

Fill both blanks to create a client-side component that safely uses a public environment variable.

NextJS
export default function ApiUrl() {
  const apiUrl = process.env.[1];
  return <p>API URL is: [2]</p>;
}
Drag options to blanks, or click blank then click option'
ANEXT_PUBLIC_API_URL
BAPI_URL
C{apiUrl}
DapiUrl
Attempts:
3 left
💡 Hint
Common Mistakes
Using server-only variables in client components.
Not wrapping variables correctly in JSX.
5fill in blank
hard

Fill all three blanks to create a server-side function that reads and returns environment variables.

NextJS
export async function getServerSideProps() {
  const secret = process.env.[1];
  const publicKey = process.env.[2];
  return {
    props: { secret, [3] }
  };
}
Drag options to blanks, or click blank then click option'
ASECRET_KEY
BNEXT_PUBLIC_KEY
CpublicKey
DNEXT_PUBLIC_SECRET
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up server and public environment variable names.
Returning props with incorrect keys.