Blog>
Snippets

Loading Environment Variables in getServerSideProps

Demonstrate how to access environment variables in Next.js inside the getServerSideProps function for server-side rendering.
export async function getServerSideProps() {
  // Access your environment variables using process.env
  const mySecret = process.env.MY_SECRET;

  // You can now pass this secret to your page as a prop
  return {
    props: { mySecret }
  };
}
This code retrieves the environment variable named 'MY_SECRET' inside the getServerSideProps function which runs on the server. It passes the retrieved environment variable to the page component as a prop.