In this blog post, we will learn how to use nvm (Node Version Manager) and autoenv together to manage Node.js versions and environment variables in your development workflow. This guide assumes you have already installed both nvm and autoenv on your system.

Why use NVM and Autoenv together?

nvm is a fantastic tool for managing multiple versions of Node.js on your system, allowing you to switch between them easily. autoenv simplifies the process of managing environment variables by automatically loading them from a .env file when you enter a directory.

By combining the two, you can set up your development environment to automatically switch to the appropriate Node.js version and load the relevant environment variables, streamlining your workflow.

Creating an .env file

First, create an .env file in the root directory of your project. This file will contain the environment variables and the Node.js version you want to use for the project.

Here’s an example of what the .env file might look like:

export NODE_ENV=development
export API_KEY=your_api_key_here
export PORT=3000
export NVM_DIR="$HOME/.nvm"
nvm use 14.17.0

In this example, we’re setting the NODE_ENV, API_KEY, and PORT environment variables. We’re also specifying the path to the nvm directory and instructing it to use Node.js version 14.17.0 for the project.

Using NVM with Autoenv

Now that you have your .env file set up, you need to configure autoenv to work with nvm. To do this, add the following line to your .autoenv.zsh or .autoenv.sh file, depending on your shell:

source "$NVM_DIR/nvm.sh"

This line ensures that the nvm command is available when autoenv loads the .env file.

Setting up your project

With the configuration complete, navigate to your project’s root directory using the terminal. You should see a message from autoenv indicating that it has loaded the .env file:

$ cd your_project_directory
autoenv:
autoenv: Loading .env
autoenv: Switching to Node.js v14.17.0

Now, the specified Node.js version and the environment variables from the .env file will be automatically set for your project.

Switching between projects

When you navigate between projects with different .env files, autoenv and nvm will automatically adjust the Node.js version and environment variables accordingly:

$ cd another_project_directory
autoenv:
autoenv: Loading .env
autoenv: Switching to Node.js v12.22.1

This makes managing different Node.js versions and environments a breeze!

Conclusion

By using nvm and autoenv in combination, you can greatly simplify the management of Node.js versions and environment variables for your projects. This will make your development process more efficient and ensure that you’re always using the correct settings for each project.