Javascript is required
ยท
1 min read

Nuxt Tip: Use Environment-Specific Configurations

Nuxt Tip: Use Environment-Specific Configurations Image

It sometimes happens that you need to have different configurations for different environments in your Nuxt.js application. In this article, I'll show you how to use environment-specific Nuxt configurations.

Let's start with a simple nuxt.config.ts file:

nuxt.config.ts
1export default defineNuxtConfig({
2  app: {
3    head: {
4      title: 'My App'
5    }
6  }
7})

For demonstration purposes, let's assume that we want to have a different title in development and production. You might be tempted to use an environment variable like this:

nuxt.config.ts
1export default defineNuxtConfig({
2  app: {
3    head: {
4      title: process.env.NODE_ENV === 'development' ? 'My App (Dev)' : 'My App'
5    }
6  }
7})

This approach is not recommended by Nuxt, instead, you should use the fully typed, per-environment overrides like $production, $development or $test in your nuxt.config file. Here's how you can do it:

nuxt.config.ts
1export default defineNuxtConfig({
2  app: {
3    head: {
4      title: 'My App'
5    }
6  },
7  $development: {
8    app: {
9      head: {
10        title: 'My App (Dev)'
11      }
12    }
13  }
14})

The $development key is a special key that allows you to define a Nuxt configuration for the development environment. This configuration is merged with the default configuration when running in development mode. This mechanism is powered by c12, a smart configuration loader available in the UnJS ecosystem.

Info

If you're authoring layers, you can also use the $meta key to provide metadata that you or the consumers of your layer might use.

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.