nuxt: Middleware Ajax Request doesn't send up cookies?

Hello everyone! I’m absolutely loving using nuxtjs for my vue app. It’s been awesome so far. Thanks for the hard work!

I seem to have run into a bug or maybe I’m misunderstanding how the middlewares should work. The documentation indicates that I can return a promise in a middleware.

Here’s what my middleware looks like. I’m using secure cookies in my app which are not accessible via JavaScript, so, the only way to check if a user is authenticated is by hitting the server. This midleware will check the authentication using my vuex method getSignedInUser.

// Middleware
export default function({ store, redirect }) {
    // If the user is not authenticated
    console.log('is authenticated?');
    if (!store.getters.isAuthenticated) {
        if (!store.getters.hasCheckedForAuthentication) {
            return new Promise((resolve, reject) => {
                store
                    .dispatch('getSignedInUser')
                    .then(() => resolve())
                    .catch(() => redirect('/admin/login'));
            });
        } else
            return redirect('/admin/login');
    }
}

(yeah, I know I probably don’t have to wrap my promise in another promise–was trying to debug)

The ajax request is super simple. I use axios with withCredentials: true.

// Get Signed in User
function getSignedInUser() {
    console.log('Send up ajax request');
    return axios.get('/api/v1/admin/user');
}

In the end, there’s no ajax request in Chrome: image

However, I know it’s hitting the server, because the logs are coming through. image

When I run the exact same vuex action from a vue method, it works.

isSignedIn() {
    this.$store.dispatch('getSignedInUser');
 }

image

So am I missing something? How can I get nuxt.js to send up the actual ajax request with the cookie during the middleware? Or should I change my strategy for authentication? I’d like to continue to use secure cookies (to protect against possible XSS attacks).

Thanks!

UPDATE: I just noticed that this issue ONLY occurs when I directly load the page with the middleware. For example, I run this middleware on the /admin page. If I directly go to localhost:3000/admin, the issue I spoke of above occurs. However, if I add a nuxt-link to my home page, linking to the /admin page and go to the page by clicking on the link, this issue doesn’t occur.

<div align="right">This question is available on Nuxt.js community (#c401)</div>

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 25 (10 by maintainers)

Most upvoted comments

I found a workaround for this that seems pretty neat to me.

------------------------ UPDATE (on 2017/09/07) ---------------------- Not really, there’s a serious security problem with doing what I suggest below. Please take a look at my next comments on this date (2017/09/07)

I was trying to use an auth.js middleware to save the logged user object in the store. For that, I make an AJAX call to /api/whoami and the backend uses cookies to decide whether the user is logged or not. So this approach has the issue described by @TibFib (things only work when the middleware is ran on the client)

middleware/auth.js

import AppApi from '~apijs'

export default function (ctx) {
    return AppApi.whoami().then((response) => {
        if(response.data.authenticated){
            ctx.store.commit('SET_LOGGED_USER', response.data.user);
        } else {
            ctx.store.commit('SET_LOGGED_USER', null);
        }
    });
}

Then I tried adding anothe middleware on nuxt.config.js, to configure axios to “forward” all headers (including cookies) to the backend:

  router: {
    middleware: ['fwdcookies', 'auth'],
  },

middleware/fwdcookies.js

import axios from '~/plugins/axios';

export default function (ctx) {
    if(ctx.isServer){
        Object.keys(ctx.req.headers).map((key)=>{
            axios.defaults.headers.common[key] = ctx.req.headers[key];
        });
    }
}

And it freaking works!

@Atinux do you foresee any problems doing that? Do you think that’s a good solution?