Looking to retrieve a cookie within Vue Router in Vue 3? Utilize the following approach within your router's `index.js

Scenario: Developing a Vue3 app with express as the API backend. Express utilizes express-sessions to create a server-side session that is transmitted to the browser and received in subsequent requests.

I am in the process of implementing a route guard to restrict access to specific routes if the session cookie is not present.

"vue": "^3.0.11",
"vue3-cookies": "1.0.1",

The NPM package that has been installed is:

https://www.npmjs.com/package/vue3-cookies

Following this, in main.js

import VueCookies from 'vue3-cookies'
app.use(VueCookies);

And then in router/index.js

function requireAuth(to,from,next){
  console.log(this);
  console.log(this.$cookies.get('_ga'))
  next();
}

const routes = [
  {
    path: '/',
    name: 'ProtectedRoute',
    component: ProtectedRoute,
    beforeEnter:requireAuth
  }

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

Error: [Vue Router warn]: Unexpected error when starting the router: TypeError: Cannot read property '$cookies' of undefined

Attempts have been made with:

this.$cookies.get('_ga')
Vue.$cookies.get('_ga')
window.$cookies.get('_ga')

However, none of them have been successful.

An attempt was also made to import Vue into the index.js file, but it failed due to the inability to import Vue into a component in Vue3 as explained in Vue.js 3: Cannot import Vue global object

The issue appears to be that this, Vue, and window are all undefined. A solution was attempted based on the suggestions here `this` undefined in vue-router beforeEach

router.beforeEach((to,from,next) => {
  console.log(router.app); //still undefined!
});

In need of assistance!

Answer №1

I found a solution that worked for me:

//router.js
import { useCookies } from "vue3-cookies";
const { cookies } = useCookies();

console.log(cookies.get('...'));

Answer №2

In Vue Router 4, the router.app property has been removed. However, you can manually add it during router setup:

// main.js
import router from './router'

const app = createApp(App)

app.use(router)
router.app = app

app.mount('#app')

You can then use this reference in the router configuration script to access

app.config.globalProperties.$cookies
(the globally added property by vue3-cookies):

// router.js
const router = createRouter({
  history: createWebHistory(),
  routes
})

function requireAuth(to, from, next) {
  const { $cookies } = router.app.config.globalProperties
  console.log('_ga', $cookies.get('_ga'))
  next()
}

export default router

Check out the demo here

Answer №3

After researching further based on tony19's suggestion, I discovered a different approach that solved my issue. I noticed that router.app was removed and my attempts to add it back manually were unsuccessful. Instead, I decided to export the app instance from my main.js file:

// main.js
export { app };

Then I imported it into the router file:

// router.js
import { app } from '...'

By doing this, I was able to access the app instance's configuration, which included the $cookies.get method:

console.log(app.$cookies.get('...'))

Answer №4

After reading Syll's answer, I realized a mistake in my code that was causing issues. Instead of using {} when setting the const, I needed to call .cookies() method on the object returned by useCookies() from the vue3-cookies library. Here is the corrected approach:

import { useCookies } from "vue3-cookies";
const cookies_manager = useCookies();

console.log(cookies_manager.cookies.get('myCookieName'));

To avoid this issue, you can simply use

const { cookies } = useCookies();
(with curly braces) instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting the issue of file URL chunks in Laravel and Vue.js

I'm currently working on a web application using Laravel and Vue. I have deployed the application to the following route on the host: https://novintech.info/panel Everything seems to be fine, except that the chunks file is referencing the wrong path ...

Upload file via AJAX immediately after downloading it (no need for storage)

Currently, I am in the process of developing a JavaScript script to safeguard an old game development sandbox website from being discarded by its owners. In order to prevent the loss of all the games on the site, I have managed to create a script that allo ...

How the React Component Class Executes OnChange Event in a Closure

When working on my React code, I found myself creating a closure by calling "onChange." class CityInput extends React.Component { constructor( props ){ super( props ); this.state = { city : "", country : "" ...

Using Vue.js to link and update dynamic form fields

I have developed a dynamic set of form inputs utilizing vue.js, where the form inputs are generated from an external list of inputs. My challenge lies in figuring out how to bind the input values back to the vue model, enabling the vue instance to access ...

Is there a way to customize the pagination dots in react-native-swiper-flatlist?

Is it possible to customize the pagination dots style for react-native-swiper-flatlist? <View style={styles.container}> <SwiperFlatList autoplay={false} autoplayLoop={false} index={0} showPagination ...

Enzyme examination: Error - anticipate(...).find was not recognized as a function

What is the reason for .find not being recognized as a function in the code snippet below? import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import { AuthorizedRoutesJest } from ...

How to access and retrieve data from a USB flash drive using Javascript

I am looking to print PDF files from a USB flash drive. I have decided to use Mozilla Firefox and the R-kiosk plugin along with the open library PDF.js, but I am facing an issue. How can I read folders and files to create a tree structure without using ...

The form submission feature is malfunctioning due to JavaScript issues

I have forms that allow file uploads (images), and I am trying to restrict the size of those images to 500KB. However, for some reason, the forms are not submitting and I am unsure why. Below is the jQuery code: $('form').on('submit', ...

Issue with MUI toggle switch not updating display and value upon clicking once

I'm currently experiencing issues with a Material UI toggle switch in my project. Initially, when the component loads, the console log displays the correct value. However, when I toggle the switch from 'yes' to 'no', the visual cha ...

`Using Twitter Bootstrap in mobile app development with javascript`

I have been utilizing Twitter Bootstrap 2.3 on one of my websites and I appreciate its responsiveness and use of media queries for mobile devices. However, I have noticed a lack of mobile-specific features, particularly linked listviews. In order to addres ...

Maintaining a reference to an element while binding event handlers in a prototype

Is there a way to utilize a bound event handler in prototype while maintaining the "this" context? It seems that doing so disrupts the default binding provided by prototype for event handlers. According to the documentation: The handler's context ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...

MongoDB date query with $gte and $le operators mm/dd/yy

Apologies in advance for any language errors. The problem I am dealing with involves a column in the database called "Date" inside the "startOn" Object. This setup creates a structure like "startOn.Date" with data format as yyyy/dd/mm. For example, if we ...

What is the best way to utilize a single npm module in multiple TypeScript files?

Question: I keep encountering the error message "error TS2451: Cannot redeclare block-scoped variable 'os'" when I try to import the same npm module in multiple TypeScript files and run the TypeScript compiler tsc. Here is an overview of my proj ...

Sending data from Ajax to PHP

I've gone through all the previous examples without success, and now I am facing a simple php question. You can find the example here. My goal is to click on a table and have the options displayed as follows: When I explicitly declare the table name ...

Steps for generating an observable that mirrors the structure of an observable array

I am in the process of creating an observable array using JSON data retrieved from the server. var ViewModel = function (data) { var self = this; self.list = ko.observableArray(data); self.selected = ko.observable(); } ...

Activating the Play button to start streaming a link

Recently delved into the world of Ionic 4 and Angular, so definitely a beginner :) Purchased a UI Template from code canyon but didn't realize I needed to code the music player part. Been trying to get a music stream playing but no luck. Came across ...

Is there a method to incorporate lists of varying types in a single v-for loop without causing any issues with type validations?

My current component is designed to display two different datasets, each with their own unique nature of data: state.articleTypeList: string[] state.renderPriceClassNameList: {[key: string]: string[]} To render both datasets within a single v-for componen ...

Creating a Rails application that dynamically fills a table with data from a

Encountering an issue with Ruby on Rails. I have a "Host Model" that contains a method which has a longer runtime. class Host < ActiveRecord::Base def take-a-while # implement logic here end Attempting to access a page where this method ru ...

An unconventional approach to utilizing Vue CLI for personal projects

Currently, I have built a Vue application with Bootstrap-Vue, Express (Node.js), and MySQL. The project is being developed using vue-cli and is in development mode. The client and server are separated into different folders to create a single-page applicat ...