0
# Context & Runtime
1
2
Nuxt instance access, runtime configuration management, and context handling utilities for modules and plugins.
3
4
## Capabilities
5
6
### Nuxt Context Access
7
8
Access the current Nuxt instance from anywhere in your module or plugin code.
9
10
```typescript { .api }
11
/**
12
* Get Nuxt instance, throws if unavailable
13
* @returns Current Nuxt instance
14
* @throws Error if no Nuxt context is available
15
*/
16
function useNuxt(): Nuxt;
17
18
/**
19
* Try to get Nuxt instance, returns null if unavailable
20
* @returns Current Nuxt instance or null
21
*/
22
function tryUseNuxt(): Nuxt | null;
23
24
/**
25
* Get direct access to Nuxt context with asyncLocalStorage
26
* @returns Current Nuxt instance or undefined
27
*/
28
function getNuxtCtx(): Nuxt | undefined;
29
30
/**
31
* Run function within Nuxt context
32
* @param nuxt - Nuxt instance to use as context
33
* @param fn - Function to run within context
34
* @returns Result of function execution
35
*/
36
function runWithNuxtContext<T>(nuxt: Nuxt, fn: T): ReturnType<T>;
37
```
38
39
**Usage Examples:**
40
41
```typescript
42
import { useNuxt, tryUseNuxt, runWithNuxtContext } from "@nuxt/kit";
43
44
// Get Nuxt instance (throws if not available)
45
export function myUtility() {
46
const nuxt = useNuxt();
47
console.log(`Nuxt version: ${nuxt.options.version}`);
48
}
49
50
// Safely try to get Nuxt instance
51
export function safeLookup() {
52
const nuxt = tryUseNuxt();
53
if (nuxt) {
54
console.log("Nuxt is available");
55
} else {
56
console.log("No Nuxt context");
57
}
58
}
59
60
// Run code with specific Nuxt context
61
const result = runWithNuxtContext(nuxtInstance, () => {
62
// This code runs with nuxtInstance as context
63
const currentNuxt = useNuxt(); // Will return nuxtInstance
64
return currentNuxt.options.dev;
65
});
66
```
67
68
### Runtime Configuration
69
70
Manage and access Nuxt runtime configuration with environment variable support.
71
72
```typescript { .api }
73
/**
74
* Access resolved Nuxt runtime configuration with environment variables applied
75
* @returns Runtime configuration object
76
*/
77
function useRuntimeConfig(): RuntimeConfig;
78
79
/**
80
* Update Nuxt runtime configuration
81
* @param runtimeConfig - Configuration values to merge
82
*/
83
function updateRuntimeConfig(runtimeConfig: Record<string, unknown>): void;
84
85
interface RuntimeConfig {
86
/** Public runtime config (available on client and server) */
87
public: Record<string, any>;
88
/** Private runtime config (server-only) */
89
private?: Record<string, any>;
90
/** App-specific configuration */
91
app: AppConfig;
92
[key: string]: any;
93
}
94
95
interface AppConfig {
96
/** Base URL for the application */
97
baseURL?: string;
98
/** Application build timestamp */
99
buildDate?: string;
100
/** Environment name */
101
env?: string;
102
[key: string]: any;
103
}
104
```
105
106
**Usage Examples:**
107
108
```typescript
109
import { useRuntimeConfig, updateRuntimeConfig } from "@nuxt/kit";
110
111
// Access runtime configuration
112
export default defineNuxtModule({
113
setup() {
114
const config = useRuntimeConfig();
115
116
console.log(`API URL: ${config.public.apiUrl}`);
117
console.log(`Secret key: ${config.secretKey}`);
118
console.log(`Base URL: ${config.app.baseURL}`);
119
}
120
});
121
122
// Update runtime configuration
123
updateRuntimeConfig({
124
public: {
125
apiVersion: "v2",
126
features: {
127
newFeature: true
128
}
129
},
130
privateKey: process.env.PRIVATE_KEY
131
});
132
133
// Module with runtime config schema
134
export default defineNuxtModule({
135
setup(options, nuxt) {
136
// Add to runtime config
137
nuxt.options.runtimeConfig = nuxt.options.runtimeConfig || {};
138
nuxt.options.runtimeConfig.public = nuxt.options.runtimeConfig.public || {};
139
140
// Add public config
141
nuxt.options.runtimeConfig.public.myModule = {
142
enabled: options.enabled,
143
endpoint: options.endpoint
144
};
145
146
// Add private config
147
nuxt.options.runtimeConfig.myModuleSecret = options.secretKey;
148
}
149
});
150
```
151
152
### Environment Variable Integration
153
154
Runtime configuration automatically resolves environment variables.
155
156
**Environment Variable Patterns:**
157
158
```bash
159
# Public config (prefixed with NUXT_PUBLIC_)
160
NUXT_PUBLIC_API_URL=https://api.example.com
161
NUXT_PUBLIC_SITE_NAME=My Site
162
163
# Private config (prefixed with NUXT_)
164
NUXT_SECRET_KEY=secret123
165
NUXT_DATABASE_URL=postgresql://...
166
167
# Nested configuration
168
NUXT_PUBLIC_FEATURES_BETA=true
169
NUXT_AUTH_GOOGLE_CLIENT_ID=google123
170
```
171
172
**Accessing Environment Variables:**
173
174
```typescript
175
import { useRuntimeConfig } from "@nuxt/kit";
176
177
export default defineNuxtModule({
178
setup() {
179
const config = useRuntimeConfig();
180
181
// Access public config (available on client)
182
const apiUrl = config.public.apiUrl; // NUXT_PUBLIC_API_URL
183
const siteName = config.public.siteName; // NUXT_PUBLIC_SITE_NAME
184
185
// Access private config (server-only)
186
const secretKey = config.secretKey; // NUXT_SECRET_KEY
187
const dbUrl = config.databaseUrl; // NUXT_DATABASE_URL
188
189
// Access nested config
190
const betaFeatures = config.public.features.beta; // NUXT_PUBLIC_FEATURES_BETA
191
const googleClientId = config.auth.google.clientId; // NUXT_AUTH_GOOGLE_CLIENT_ID
192
}
193
});
194
```
195
196
### Legacy Context (Deprecated)
197
198
```typescript { .api }
199
/**
200
* Direct access to Nuxt global context (deprecated)
201
* @deprecated Use useNuxt() instead
202
*/
203
const nuxtCtx: any;
204
```
205
206
## Types
207
208
```typescript { .api }
209
interface Nuxt {
210
/** Nuxt configuration options */
211
options: NuxtOptions;
212
/** Hook system */
213
hooks: Hookable;
214
/** Hook registration method */
215
hook: Hookable['hook'];
216
/** Hook calling method */
217
callHook: Hookable['callHook'];
218
/** Ready promise */
219
ready: () => Promise<void>;
220
/** Cleanup method */
221
close: () => Promise<void>;
222
/** Module container */
223
moduleContainer?: any;
224
/** Server instance */
225
server?: any;
226
/** Renderer instance */
227
renderer?: any;
228
[key: string]: any;
229
}
230
231
interface NuxtOptions {
232
/** Development mode flag */
233
dev: boolean;
234
/** Server-side rendering flag */
235
ssr: boolean;
236
/** Application directory */
237
srcDir: string;
238
/** Build directory */
239
buildDir: string;
240
/** Root directory */
241
rootDir: string;
242
/** Runtime configuration */
243
runtimeConfig: RuntimeConfig;
244
/** Application configuration */
245
app: AppConfig;
246
[key: string]: any;
247
}
248
```