How to use Vue with cookies
Managing cookies in Vue applications enables persistent data storage across browser tabs and sessions, essential for authentication tokens and user preferences. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented cookie-based state management in Vue applications throughout my 11 years of framework development. The most reliable approach is using the js-cookie library for simplified cookie operations with automatic encoding and expiration handling. This method provides cross-tab synchronization and server-side access to stored data.
Use js-cookie library to manage cookies in Vue with reactive state synchronization.
import { ref, watch } from 'vue'
import Cookies from 'js-cookie'
export default {
setup() {
const userTheme = ref(Cookies.get('theme') || 'light')
watch(userTheme, (newTheme) => {
Cookies.set('theme', newTheme, { expires: 365 })
})
const toggleTheme = () => {
userTheme.value = userTheme.value === 'light' ? 'dark' : 'light'
}
return { userTheme, toggleTheme }
}
}
Here the component initializes state from an existing cookie or uses a default value. A watcher automatically updates the cookie when state changes, setting an expiration of 365 days. The Cookies.set() method handles URL encoding and cookie formatting automatically. Cookies are accessible across all tabs and to server-side code, making them ideal for authentication and preferences.
Best Practice Note:
This is the approach we use in CoreUI Vue applications for theme preferences and authentication tokens. Always set appropriate expiration dates, use secure and httpOnly flags for sensitive data, and consider cookie size limits (4KB) when storing data. For authentication tokens, implement proper security measures and CSRF protection.



