admin管理员组

文章数量:1122832

I'm implementing a "Contact Us" email functionality where I need environment variables for sensitive information such as a username and password for email authentication PRIVATE_KEY and a public API key PUBLIC_KEY.

Locally, my .env file contains the following:

#.env

PUBLIC_KEY=PUBLIC
PRIVATE_KEY=PRIVATE

This works perfectly in my local development environment. However, when I deploy to platforms like Vercel or AWS Amplify, these environment variables are undefined, even though I’ve correctly defined them in the platforms' environment variable settings.

To work around this issue, I added the following configuration to next.config.js

module.exports = {
  env: {
    PUBLIC_KEY: 'PUBLIC',
    PRIVATE_KEY: 'PRIVATE',
  },
};

This resolves the issue, but I have concerns about security because, according to the Next.js documentation, any variables added to the env key in next.config.js will be included in the JavaScript bundle and sent to the client. Here's the key excerpt:

Environment variables specified this way will always be included in the JavaScript bundle. Prefixing the environment variable name with NEXT_PUBLIC_ only has an effect when specifying them through the environment or .env files.

My use case involves:

  1. Using PUBLIC_KEY on client-side pages (e.g., in use client components). This is intentional and expected since it's safe to expose public API keys.
  2. Using PRIVATE_KEY only in dynamic server-side code (e.g., API routes), which must remain secure and never be included in client-side bundles.

However, based on the documentation, adding PRIVATE_KEY to the env key in next.config.js would expose it in the client-side JavaScript bundle, which is a serious security concern. This makes me wonder if my implementation is truly secure or if my sensitive keys, like PRIVATE_KEY, are inadvertently being leaked to the client.

Could you clarify:

Why defining environment variables in the deployment platform doesn’t work? Whether there’s a secure way to use sensitive environment variables PRIVATE_KEY only on the server-side without risk of exposure?

I tried adding PUBLIC_KEY and PRIVATE_KEY to .env for local development and the deployment platform’s environment variables. Locally, it worked as expected, but in deployment, they were undefined. Adding them to next.config.js fixed it, but I expected the platform environment variables to work without exposing sensitive keys.

本文标签: nextjsEnsure Private Key Environment Variables NextJS are private nextconfigjsStack Overflow