0
# Storage and State Management
1
2
Persistent storage solutions using cookies, IndexedDB, and JWT token handling for maintaining application state.
3
4
## Capabilities
5
6
### useCookies
7
8
Reactive cookie management with automatic reactivity and SSR support.
9
10
```typescript { .api }
11
/**
12
* Reactive cookie management with automatic reactivity
13
* @param dependencies - Array of cookie names to watch for changes
14
* @param options - Configuration options
15
* @param cookies - Custom cookie instance (for SSR)
16
* @returns Cookie management interface
17
*/
18
function useCookies(
19
dependencies?: string[] | null,
20
options?: {
21
doNotParse?: boolean;
22
autoUpdateDependencies?: boolean;
23
},
24
cookies?: Cookie
25
): {
26
/** Get a cookie value by name */
27
get: <T = any>(...args: Parameters<Cookie['get']>) => T;
28
/** Get all cookies as an object */
29
getAll: <T = any>(...args: Parameters<Cookie['getAll']>) => T;
30
/** Set a cookie value */
31
set: (...args: Parameters<Cookie['set']>) => void;
32
/** Remove a cookie */
33
remove: (...args: Parameters<Cookie['remove']>) => void;
34
/** Add change listener */
35
addChangeListener: (...args: Parameters<Cookie['addChangeListener']>) => void;
36
/** Remove change listener */
37
removeChangeListener: (...args: Parameters<Cookie['removeChangeListener']>) => void;
38
};
39
40
/**
41
* Create a cookie factory for SSR environments
42
* @param req - HTTP request object (for SSR)
43
* @returns useCookies factory function
44
*/
45
function createCookies(req?: IncomingMessage): (
46
dependencies?: string[] | null,
47
options?: { doNotParse?: boolean; autoUpdateDependencies?: boolean }
48
) => ReturnType<typeof useCookies>;
49
```
50
51
**Usage Examples:**
52
53
```typescript
54
import { useCookies } from "@vueuse/integrations/useCookies";
55
56
// Basic cookie management
57
const cookies = useCookies(['user-preferences', 'auth-token']);
58
59
// Set cookies
60
cookies.set('theme', 'dark', { path: '/' });
61
cookies.set('user-id', '12345', {
62
expires: new Date(Date.now() + 86400000) // 1 day
63
});
64
65
// Get cookies
66
const theme = cookies.get('theme'); // 'dark'
67
const allCookies = cookies.getAll();
68
69
// Remove cookies
70
cookies.remove('old-setting');
71
72
// Auto-update dependencies
73
const cookies = useCookies(null, {
74
autoUpdateDependencies: true
75
});
76
77
// SSR usage
78
import { createCookies } from "@vueuse/integrations/useCookies";
79
80
// In your server-side code
81
const cookieFactory = createCookies(req);
82
const cookies = cookieFactory(['session']);
83
```
84
85
### useIDBKeyval
86
87
Reactive IndexedDB storage with automatic persistence and type safety.
88
89
```typescript { .api }
90
/**
91
* Reactive IndexedDB storage with automatic persistence
92
* @param key - IndexedDB key for storage
93
* @param initialValue - Initial value if key doesn't exist
94
* @param options - Configuration options
95
* @returns Reactive storage interface
96
*/
97
function useIDBKeyval<T>(
98
key: IDBValidKey,
99
initialValue: MaybeRefOrGetter<T>,
100
options?: UseIDBOptions<T>
101
): UseIDBKeyvalReturn<T>;
102
103
interface UseIDBKeyvalReturn<T> {
104
/** Reactive data value with automatic persistence */
105
data: RemovableRef<T>;
106
/** Whether initial load from IndexedDB is complete */
107
isFinished: ShallowRef<boolean>;
108
/** Manually set the value */
109
set: (value: T) => Promise<void>;
110
}
111
112
interface UseIDBOptions<T> extends ConfigurableFlush {
113
/** Deep watch the data for changes */
114
deep?: boolean; // default: true
115
/** Error callback function */
116
onError?: (error: unknown) => void;
117
/** Use shallow ref for data */
118
shallow?: boolean; // default: false
119
/** Write initial/default values to storage */
120
writeDefaults?: boolean; // default: true
121
/** Custom serializer for complex data types */
122
serializer?: Serializer<T>;
123
}
124
125
interface Serializer<T> {
126
/** Deserialize data from storage */
127
read: (raw: unknown) => T;
128
/** Serialize data for storage */
129
write: (value: T) => unknown;
130
}
131
132
interface RemovableRef<T> extends Ref<T> {
133
/** Remove the value from storage and reset to initial */
134
$remove: () => void;
135
}
136
```
137
138
**Usage Examples:**
139
140
```typescript
141
import { useIDBKeyval } from "@vueuse/integrations/useIDBKeyval";
142
143
// Basic usage
144
const { data, isFinished } = useIDBKeyval('user-settings', {
145
theme: 'light',
146
language: 'en'
147
});
148
149
// Wait for initial load
150
watchEffect(() => {
151
if (isFinished.value) {
152
console.log('Settings loaded:', data.value);
153
}
154
});
155
156
// Update data (automatically persisted)
157
data.value.theme = 'dark';
158
159
// Remove from storage
160
data.$remove();
161
162
// With custom serializer
163
const { data } = useIDBKeyval('complex-data', new Map(), {
164
serializer: {
165
read: (value) => new Map(value as any),
166
write: (value) => Array.from(value.entries())
167
}
168
});
169
170
// Error handling
171
const { data } = useIDBKeyval('my-key', null, {
172
onError: (error) => {
173
console.error('IndexedDB error:', error);
174
}
175
});
176
```
177
178
### useJwt
179
180
JWT token decoding with reactive payload and header extraction.
181
182
```typescript { .api }
183
/**
184
* JWT token decoding with reactive payload and header extraction
185
* @param encodedJwt - Encoded JWT token string
186
* @param options - Configuration options
187
* @returns Decoded JWT header and payload
188
*/
189
function useJwt<
190
Payload extends object = JwtPayload,
191
Header extends object = JwtHeader,
192
Fallback = null
193
>(
194
encodedJwt: MaybeRefOrGetter<string>,
195
options?: UseJwtOptions<Fallback>
196
): UseJwtReturn<Payload, Header, Fallback>;
197
198
interface UseJwtReturn<Payload, Header, Fallback> {
199
/** Reactive JWT header */
200
header: ComputedRef<Header | Fallback>;
201
/** Reactive JWT payload */
202
payload: ComputedRef<Payload | Fallback>;
203
}
204
205
interface UseJwtOptions<Fallback> {
206
/** Fallback value when decoding fails */
207
fallbackValue?: Fallback; // default: null
208
/** Error callback function */
209
onError?: (error: unknown) => void;
210
}
211
212
// Standard JWT interfaces
213
interface JwtPayload {
214
iss?: string;
215
sub?: string;
216
aud?: string | string[];
217
exp?: number;
218
nbf?: number;
219
iat?: number;
220
jti?: string;
221
[key: string]: any;
222
}
223
224
interface JwtHeader {
225
typ?: string;
226
alg?: string;
227
[key: string]: any;
228
}
229
```
230
231
**Usage Examples:**
232
233
```typescript
234
import { useJwt } from "@vueuse/integrations/useJwt";
235
import { ref } from 'vue';
236
237
// Basic JWT decoding
238
const token = ref('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');
239
const { header, payload } = useJwt(token);
240
241
// Access token data
242
console.log('Algorithm:', header.value?.alg);
243
console.log('User ID:', payload.value?.sub);
244
console.log('Expires:', new Date((payload.value?.exp || 0) * 1000));
245
246
// Custom payload type
247
interface CustomPayload {
248
userId: string;
249
role: string;
250
permissions: string[];
251
}
252
253
const { payload } = useJwt<CustomPayload>(token);
254
console.log('Role:', payload.value?.role);
255
256
// With fallback value and error handling
257
const { header, payload } = useJwt(token, {
258
fallbackValue: { error: 'Invalid token' },
259
onError: (error) => {
260
console.error('JWT decode error:', error);
261
}
262
});
263
264
// Check token expiration
265
const isTokenExpired = computed(() => {
266
const exp = payload.value?.exp;
267
return exp ? Date.now() >= exp * 1000 : true;
268
});
269
```