How to use Nuxt SSR middleware with cookies?

Viewed 435

I have a SSR Nuxt app. There is a middleware in the page code. I dont know is I can use js-cookies library in that middleware and if it will work as I expected. I need to get and set up the cookie in browser and also get the cookie value on the server. All this steps in the middleware.

I mean

  1. check if cookie is set via Cookies.get(key)
  2. if not then set up the cookie via Cookies.set(key, value)
  3. redirect to the server where I want to get this cookie value

Code should look like

async middleware(context) {
    const token = context.route.query.token;
    if (!token) {
        const cookieToken = Cookies.get('cookieToken');

        if( !cookieToken ) {
            Cookies.set('cookieTokne', nanoId());
        }

        const result = await context.$api.campaignNewShare.createNewShare();
        context.redirect({'name': 'campaigns-new', 'query': {token: result.data.token}});
    }
},

Am I able to get cookie after the set on the server and can I get it in the browser after the redirect? I need to ensure both set and get in this middleware at once.

1 Answers

Use nuxt universal cookies and register on your modules, this way you can access the module everywhere on your nuxt app.

Using your code as example:

async middleware(context) {
    const token = context.route.query.token;

    if (!token) {
        const cookieToken = context.$cookies.get('cookieToken');

        if( !cookieToken ) {
            context.$cookies.set('cookieToken', nanoId());
        }

        const result = await context.$api.campaignNewShare.createNewShare();
        context.redirect({'name': 'campaigns-new', 'query': {token: result.data.token}});
    }
},
Related