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:
However, I know it's hitting the server, because the logs are coming through.
When I run the exact same vuex action from a vue method, it works.
isSignedIn() {
this.$store.dispatch('getSignedInUser');
}
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.