How to share envs in a monorepo with vite and nextjs apps

tgmarinhodev

Thiago Marinho

Posted on May 4, 2023

How to share envs in a monorepo with vite and nextjs apps

To share environment variables between two projects in a monorepo, with specific prefixes for each project, you can create a .env.shared file with common environment variables and then use scripts to create specific .env files for each project. Here's how to do that:

Create a .env.shared file at the root of the monorepo with the common environment variables:

SECRET_KEY=your_secret_key
API_URL=your_api_url
Enter fullscreen mode Exit fullscreen mode

Create a script to generate specific .env files for each project. In the example below, we will create a generate-env.js file at the root of the monorepo:

// generate-env.js
const fs = require('fs');
const path = require('path');

const envShared = path.join(__dirname, '.env.shared');
const envVite = path.join(__dirname, 'vite-project', '.env');
const envNext = path.join(__dirname, 'next-project', '.env');

const sharedVars = fs.readFileSync(envShared, 'utf-8').split('\n');

const viteVars = sharedVars.map((line) => {
  if (line.startsWith('SECRET_KEY') || line.startsWith('API_URL')) {
    return `VITE_PUBLIC_${line}`;
  }
  return line;
});

const nextVars = sharedVars.map((line) => {
  if (line.startsWith('SECRET_KEY') || line.startsWith('API_URL')) {
    return `NEXT_PUBLIC_${line}`;
  }
  return line;
});

fs.writeFileSync(envVite, viteVars.join('\n'), 'utf-8');
fs.writeFileSync(envNext, nextVars.join('\n'), 'utf-8');
Enter fullscreen mode Exit fullscreen mode

Run the generate-env.js script to generate the specific .env files for each project:

node generate-env.js
Enter fullscreen mode Exit fullscreen mode

This will create an .env file in the vite-project folder with environment variables prefixed with VITE_PUBLIC_ and an .env file in the next-project folder with environment variables prefixed with NEXT_PUBLIC_.

Now, each project will have its own .env file with the correctly prefixed environment variables. Be sure to add the generated .env files to your .gitignore rules to prevent committing sensitive information to the repository.

Remember to run the generate-env.js script whenever you make changes to the .env.shared file to update the specific project .env files. You can also add this script as a step in your build or deployment process.

💖 💪 🙅 🚩
tgmarinhodev
Thiago Marinho

Posted on May 4, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related