I want to have a theme cookie where I save the current theme. I’m using VueUse’s useCookies to do it on SPA mode, but it fails on SSR mode. The documentation says I need to use createCookies function instead an pass in my node request object which is of type IncomingMessage. But the problem is I’m using Laravel/Inertia and don’t know what to pass in or how. Here’s the code I’m using:
// AppLayout.vue
import { useThemes } from '@/stores/useThemes'
const themes = useThemes()
// useThemes.ts
import { createCookies, useCookies } from '@vueuse/integrations/useCookies'
import { defineStore } from 'pinia'
import { ref } from 'vue'
export type Theme = string
export const useThemes = defineStore('themes', () => {
const cookies = useCookies(['theme'])
const theme = ref(cookies.get('theme') || 'default')
/**
* @field General themes
*/
const generalThemes: Theme[] = ['Default', 'Light', 'Dark']
/**
* @field Light themes
*/
const lightThemes: Theme[] = [
'Cupcake',
'Corporate',
'Fantasy',
'Autumn',
'Winter',
'Limonade',
'Garden',
'Retro',
'Cyberpunk',
'Valentine',
'Nord',
]
/**
* @field Dark themes
*/
const darkThemes: Theme[] = ['Coffee', 'Aqua', 'Night', 'Sunset', 'Halloween', 'Business']
/**
* Set theme by string name
* @param {string} lang Language to be set
*/
function setTheme(themeName: string) {
if (
themeName != null &&
themeName != undefined &&
themeName.trim() != '' &&
(generalThemes.includes(capitalize(themeName)) ||
lightThemes.includes(capitalize(themeName)) ||
darkThemes.includes(capitalize(themeName)))
) {
theme.value = themeName
cookies.set('theme', theme.value)
}
}
/**
* Capitalize a string's first letter
* @param {string} value String to be capitalized
*/
function capitalize(value: string): string {
return value
.split(' ')
.map((word) => {
return word[0].toUpperCase() + word.substring(1)
})
.join(' ')
}
/**
* Initialize theme if not set
*/
function initTheme() {
console.log(theme.value)
setTheme(theme.value)
}
return { theme, initTheme, setTheme, generalThemes, lightThemes, darkThemes }
})
The line const cookies = useCookies(['theme']) throws error in SSR mode and must be replaced by createCookies. Here’s the Laravel side:
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;
use IlluminateSupportFacadesCookie;
use InertiaInertia;
class PageController extends Controller {
public function home(Request $req): InertiaResponse {
return Inertia::render('Home', [
'canLogin' => Route::has('login'),
'canRegister' => Route::has('register'),
'themeCookie' => $req->cookie('theme') ?? 'default',
'animatedCookie' => boolval($req->cookie('animated')) ?? true,
]);
}
}
Note that VueUse’s useCookies uses universal-cookie package internally.