docs: update runtime-config section (#4285)

Co-authored-by: Sébastien Chopin <seb@nuxtjs.com>
This commit is contained in:
pooya parsa 2022-04-12 12:04:15 +02:00 committed by GitHub
parent 0457125ebd
commit d2b4e60963
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 42 additions and 33 deletions

View File

@ -1,25 +1,34 @@
# Runtime Config
Nuxt provides an API to define the runtime config within your application and API routes.
Nuxt provides a runtime config API to expose config within your application and server routes with the ability to update them at runtime using environment variables.
## Exposing runtime config
To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your `nuxt.config` file, using either the [`runtimeConfig` options](/guide/directory-structure/nuxt.config#runtimeconfig) (based on whether you want it to be accessible on the client-side part of your app or not).
To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your `nuxt.config` file, using the [`runtimeConfig` option](/guide/directory-structure/nuxt.config#runtimeconfig).
**Example:**
```ts [nuxt.config.ts]
export default defineNuxtConfig({
runtimeConfig: {
API_SECRET: '123', // the private keys which should not be exposed to public
// The private keys which are only available within server-side
apiSecret: '123',
// Keys within public, will be also exposed to the client-side
public: {
API_BASE: '/api',
apiBase: '/api'
}
},
}
})
```
When adding `API_BASE` to the `runtimeConfig.public`, Nuxt adds it to the pages' payload. This way we can universally access `API_BASE` in both server and browser.
When adding `apiBase` to the `runtimeConfig.public`, Nuxt adds it to each page payload. We can universally access `apiBase` in both server and browser.
```js
const runtimeConfig = useRuntimeConfig()
console.log(runtimeConfig.apiSecret)
console.log(runtimeConfig.public.apiBase)
```
### Environment Variables
@ -28,50 +37,54 @@ Nuxt CLI has built-in [dotenv](https://github.com/motdotla/dotenv) support.
In addition to any process environment variables, if you have a `.env` file in your project root directory, it will be automatically loaded into `process.env` and accessible within your `nuxt.config` file and modules.
Runtime config values are automatically replaced by matching environment variables at runtime.
**Example:**
```sh [.env]
BASE_URL=https://nuxtjs.org
API_SECRET=api_secret_token
NUXT_API_SECRET=api_secret_token
NUXT_PUBLIC_BASE_URL=https://nuxtjs.org
```
```ts [nuxt.config.ts]
export default defineNuxtConfig({
runtimeConfig: {
API_SECRET: process.env.API_SECRET,
apiSecret: '',
public: {
BASE_URL: process.env.BASE_URL,
apiBase: '', // Or a default value
}
},
})
```
**💡 Tip:** While it is not necessary, by using identical runtime config names as env variables, you can easily override them in production using platform environment variables.
## Accessing runtime config
### Vue app
Within the Vue part of your Nuxt app, you will need to call `useRuntimeConfig()` to access the runtime config.
**Note:** Behavior is different between client side and server side:
**Note:** Behavior is different between the client-side and server-side:
- On client side, only `runtimeConfig.public` is available and the object is both writable and reactive.
- On server side, both `runtimeConfig.public` and `runtimeConfig` are merged and the object is read-only to avoid context sharing.
- On the client-side, only keys in `public` are available, and the object is both writable and reactive.
The entire runtime config is available on the server-side, but it is read-only to avoid context sharing.
```vue
<template>
<div>
<div>Token: {{ config.API_AUTH_TOKEN }}</div>
<div>Check developer console!</div>
</div>
</template>
<script setup>
const config = useRuntimeConfig()
console.log('Runtime config:', config)
if (process.server) {
console.log('API secret:', config.apiSecret)
}
</script>
```
**🛑 Security note:** Never use example above if `API_AUTH_TOKEN` is a private config. Even if you use `runtimeConfig`, you still have to be careful that you do not expose such config to either payload or html!
**🛑 Security note:** Be careful not to expose runtime config keys to the client-side by either rendering them or passing them to `useState`.
::alert{icon=👉}
**`useRuntimeConfig` only works during `setup` or `Lifecycle Hooks`**.
@ -81,46 +94,42 @@ const config = useRuntimeConfig()
If you want to use the runtime config within any (custom) plugin, you can use `useRuntimeConfig()` inside of your `defineNuxtPlugin` function.
For example:
For Example:
```ts
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
const url = process.server ? config.serverUrl : config.clientUrl
// Do something with url & isServer.
console.log('API base URL:', config.public.apiBase)
});
```
### API routes
### Server Routes
Within the API routes, you can access runtime config by directly importing from virtual `#nitro`.
You can access runtime config within the server routes as well using `useRuntimeConfig`.
```ts
import { useRuntimeConfig } from '#nitro'
const config = useRuntimeConfig()
export default async () => {
const result = await $fetch('https://my.api.com/test', {
headers: {
Authorization: `Bearer ${config.API_AUTH_TOKEN}`
Authorization: `Bearer ${useRuntimeConfig().apiSecret}`
}
})
return result
}
```
### Typing runtime config
### Manually Typing Runtime Config
Currently it is possible to manually type your runtime config.
Nuxt tries to automatically generate a typescript interface from provided runtime config using [unjs/untyped](https://github.com/unjs/untyped)
It is also possible to type your runtime config manually:
```ts [index.d.ts]
declare module '@nuxt/schema' {
interface runtimeConfig {
interface RuntimeConfig {
apiSecret: string
public: {
testConfig: string
apiBase: string
}
}
}