0 day streak
javascript / intermediate
Snippet

Scoping Dependency Injection Keys with JavaScript Symbols in Vue

Using JavaScript Symbol primitives as injection tokens guarantees collision-free provide/inject dependencies across large Vue component trees.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { provide, inject } from 'vue';
export const AUTH_CONTEXT_KEY = Symbol('AuthContext');
export function provideAuth(authService) {
provide(AUTH_CONTEXT_KEY, authService);
}
export function useAuth() {
const auth = inject(AUTH_CONTEXT_KEY);
if (!auth) {
throw new Error('useAuth must be called within an AuthProvider scope');
}
return auth;
}
vue
Breakdown
1
export const AUTH_CONTEXT_KEY = Symbol('AuthContext');
Creates a unique, immutable Symbol token used as the DI lookup key.
2
provide(AUTH_CONTEXT_KEY, authService);
Registers the dependency under the unique Symbol key.
3
const auth = inject(AUTH_CONTEXT_KEY);
Retrieves the value bound to the specific Symbol identifier.
4
if (!auth) throw new Error(...);
Validates that the required dependency is present in the ancestor hierarchy.