Menu
Documentation

Nuxt configuration

nuxt.config.js

A Nuxt application is configured through the nuxt.config.ts file. In this file, we can setup core features of nuxt, enable modules, configure them, extend from other layers, and more.

This is an overview of the nuxt configuration file. It's used to change the way nuxt works (disable server-side rendering, change the build directory, etc, apply cache rules to specific routes, ...)

ts
export default defineNuxtConfig({
  extends: [
    // register layers
  ],
  modules: [
    // register modules
  ],

  // rest of your nuxt config ...
})

Runtime config

Everything defined in the <app>/nuxt.config.ts file is not exposed in either the client or the server. To expose a variable to the client, you need to use the runtimeConfig property. This property is used to expose variables to the client, and to the server.

ts
export default defineNuxtConfig({
  runtimeConfig: {
    // expose variables only to server
    secretKey: 'my-private-key',

    public: {
      // expose variables to both server and client
      mapboxToken: 'my-public-token'
    }
  }
})

The runtime config can then be accessed in the server using the useRuntimeConfig nuxt composable:

ts
export default defineEventHandler((event) => {
  const config = useRuntimeConfig()
  // config.secretKey
  // config.public.mapboxToken
})

And in the client using same composable, note that you only have access to the public variables:

vue
<script setup lang="ts">
const config = useRuntimeConfig()
// config.public.mapboxToken
</script>

Environment variables

When using the runtimeConfig property, you can use environment variables to define their value. This is useful when you want to use different values for different environments.

Like seen in the previous example, you can define the NUXT_SECRET_KEY and NUXT_PUBLIC_MAPBOX_TOKEN value using an environment variable.

During development, or at build time, you can use .env files to define environment variables. These files are located at the root of your project and are named .env and .env.local. Note that when running the production build, no .env file is used.


Useful resources: