Cover image for How to dynamically import components based on a env variable in NextJS

How to dynamically import components based on a env variable in NextJS

NextJS
React

December 08, 2022

Cover image for How to dynamically import components based on a env variable in NextJS
Photo by Barth Bailey on Unsplash

You can dynamically import a component based on a environment variable in the .env file using NextJS dynamic feature

At build time, NextJS will import the proper component.

This is useful when you are migrating some components.

For example let's suppose have 2 folders components-new and components-old.

With the following code we can import any of those based on the environment variable

const MyComponent = dynamic(() => {
  return process.env.USE_OLD_COMPONENTS === 'false'
    ? import('../components-new/components/myComponent/MyComponent')
    : import('../components-old/components/myComponent/MyComponent')
});