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

Convert the jQuery functions click(), hide(), and fadeIn() into their equivalent native JavaScript functionalities

I'm determined to speed up my page by reducing requests. Does anyone have a solution for keeping the functionality of the code below without having to load the entire JQuery library? $("#div1").click(function () { $("#div2).hide(); $("#div3). ...

Remove the </div> text and replace it with nothing

I'm attempting to substitute the end tag div with an empty string. Here is my code: $('#textDiv').html().replace(/'</div>'/g,'').replace(/<div>/g,'\n') This is the HTML: <div id='tex ...

Access an HTML page programmatically using JavaScript

Make sure to have a confirmation window pop up before submitting the form, and after confirming submission (by clicking OK), redirect to a confirmation page. Here's an example code snippet: <button type="submit" value="Save" id="Save" onclick="cl ...

When attempting to use JQuery autocomplete, the loading process continues indefinitely without successfully triggering the intended function

Currently, I am utilizing JQuery autocomplete to invoke a PHP function via AJAX. Below is the code snippet I am working with: $("#client").autocomplete("get_course_list.php", { width: 260, matchContains: true, selectFirst: false }); Upon execution, ...

Is there a way to ensure that GIFs in jQuery Mobile always start from the beginning?

My cross-platform mobile app built with jQuery Mobile is a small quiz application. After each correct or wrong answer, I display a 3-second GIF. Currently, I have set up the code to show the GIF for 3 seconds before moving on to the next page: else if ($. ...

Issues encountered when passing JavaScript object to PHP

I'm attempting to transmit my JavaScript object to PHP using JSON.stringify() JavaScript: $('#save').on('click touch', function(){ obj = { "1" : { "1" : "hey", "2" : "hay" }, ...

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Proper method for validating Jwt

Below is the code I have composed: jwt.verify(token.split(':')[1], 'testTest') I am attempting to verify this code in order for it to return true and proceed. The jwt being mentioned here serves as an example payload. Any suggestions ...

Issue with AngularJS directive: Isolated scope preventing values from being inserted into template

After setting up the directive below: angular.module('news.directives', []) .directive('newsArticle', function($location, $timeout) { return { restrict: 'AE', replace: 'true&apo ...

JavaScript onClick event not functioning properly on iOS devices

I have created a code that can detect when a user clicks on a cell in a table and retrieves the background color set for that cell. Everything works perfectly on my desktop computer, but when I attempt to use my iPad, it does not respond. I attempted to u ...

Resolving the Table Issue with 'onclick' in Javascript

Apologies for the lack of creativity in the title, I struggled to come up with something fitting. Currently, I am engaged in the development of a user-friendly WYSIWYG site builder. However, I have encountered an obstacle along the way. I've devised ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

Load the dropdown menu with JSON data but encounter an error: SyntaxError caused by an unexpected token `{` in

I am currently working on populating a dropdown menu with the values of the 'styleName' field from a JSON data file. Here is an example of my JSON data: {"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlin ...

The custom tab component in React is currently not accepting the "disabledTabs" prop

I have designed a tab component as shown below: tab/index.jsx import React from 'react'; import TabHeader from './header'; import TabBody from './body'; import TabHeaderList from './header/list'; import TabBodyList ...

The date error from day.js in Firefox is not valid

My date is formatted as 2022-01-27 09:23:48 UTC and I am trying to parse it into MMMM-DD-YYYY format (Jan-27-2022) using day.js. The parsing works well in Chrome, but Firefox returns an 'Invalid' result. import dayjs from "dayjs" const ...

Can anyone recommend a high-quality jQuery lightbox replica?

Key Features Needed: Customizable with CSS Capable of handling forms, not just images Extensively documented Please provide any recommendations and suggestions for suitable options. Thank you in advance ...

Tips for displaying a category name only once if it has already been rendered in a map function

My scenario involves a variety of categories in which pharmaceutical drugs are classified. Each individual drug belongs to a specific class. Currently, my code iterates through all the categories from the category array and places drugs underneath them if ...

Exploring the Junction of Vue-Router and Gsap ScrollTrigger

I'm encountering some issues with vue-router and the gsap scrolltrigger plugin. I have several vue components that utilize scrolltrigger, but when I navigate to a different page and then return to the page with the scrolltrigger effect, it fails to tr ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Forwarding requests via middleware in next.js 13 AppDir: true

I am currently working on implementing a redirect feature in next.js 13 when the jwt back-end is not received. This is being done with the appdir activated. This is the code in my middleware.ts file: import { NextResponse } from 'next/server' im ...