I am facing a challenge in my Vue 3 project where I need to securely store the access token for the logged-in user using cookies. To achieve this, I have integrated the 'vue-cookies' npm package into my application.
<While the cookie implementation works seamlessly within components, I encountered an issue when attempting to access cookies outside of components.
Below is an excerpt from my main.ts file:
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import VueCookies from 'vue-cookies'
import router from './router'
import App from './App.vue'
import './assets/main.css'
const app = createApp(App)
app.use(createPinia())
app.use(router)
app.use(VueCookies, { expires: '15m' })
app.mount('#app')
Inside the "LoginItem.vue" component, I successfully retrieved the access token using $cookies within the script tags:
// ...
const $cookies = inject<VueCookies>('$cookies')
const token = ref('')
// ...
onMounted(() => {
const accessToken = $cookies?.get('accessToken')
if (accessToken) {
token.value = accessToken
}
})
However, I wanted to create a global module or file to handle common operations with the access token and attempted to do so in a separate file named "auth.ts". Here's the code snippet:
import { inject } from 'vue'
import type { VueCookies } from 'vue-cookies'
const $cookies = inject<VueCookies>('$cookies')
export const getToken = (): string => {
return $cookies?.get('accessToken')
}
Unfortunately, the $cookies variable always returns undefined in this context. How can I resolve this issue?
Furthermore, I'm unsure if managing access tokens in this manner aligns with the recommended approach in Vue 3. Should I explore alternative methods for handling access tokens within my application?