Consider this example:
secret.vue
<template>
<div>Hello, {{user.email}}!</div>
</template>
<script>
import Vue from 'vue'
export default {
middleware: 'authenticated',
async asyncData ({ req }) {
// executes even after the middleware redirects
let { body } = await Vue.http.get('user')
return {
title: 'Secret Page',
user: body
}
},
head () {
return {
title: this.title
}
}
}
</script>
<style>
</style>
middleware/authenticated.js
export default function ({ store, redirect }) {
if (!store.getters.isAuthenticated) {
return redirect('/auth/sign-in')
}
}
For server-side navigation redirect works as expected and component's asyncData never invokes. For client-side it invokes and renders error page with 401 HTTP code
Hello, I have the exact same problem (with both asyncData and fetch methods).
The AuthRoutes example does not use a middleware but checks for auth before running request) ; but I think a hotfix is needed for client side behavior since Nuxt lifecycle has to trigger middleware(s) before data() and fetch()
Same problem when middleware is at layout level.
It affects layout as well
Forgot to close it but it's fixed since alpha release :)
Nuxt v1.1.1
The same phenomenon as this is occurring.
I wrote a micro sample.
$ git clone https://bitbucket.org/sdr0x07b6/nuxt-redirect-test.git
$ cd nuxt-redirect-test && yarn && yarn dev
https://redirect-qhgkceudmu.now.sh/
Since page1 requires authentication, asyncData should not be executed.
There is no problem accessing page1 from the redirect destination page.
Problems occur when accessing page1 from a page other than the redirect destination.
The same is true even if the redirect destination is other than top.
Is this expected behavior?
Hey @sdr0x07b6
Thank you for your reproduction repository, I am looking at it and come back to your quickly.
@sdr0x07b6 I just made a commit to fix this behaviour, the release will really soon
I still have a similar issue. My middleware is set up so it handles token refresh, authentication and logout depending on the state. The main problem I have, is that when the user is not authenticated and goes to "/", he should either be redirected to "/login" or be logged out depending if cookies exist (both handled by initAuth action), however, I still see the page for a split second, it also fires fetch and mounted(), and then gets redirected. I have tried having initAuth return a promise and await in middleware but this doesnt seem to work..
middleware/auth.js
export default function(context) {
//3 possibilities
//not authenticated -> try to log in
//authenticated & both tokens too old -> logout
//authenticated & refresh token valid & token invalid -> refresh
if (!context.store.getters["auth/isAuthenticated"]) {
console.info("[MIDDLEWARE] Not authenticated, reading data from cookie...");
context.store.dispatch("auth/initAuth");
} else if (
context.store.getters["auth/isAuthenticated"] &&
new Date() > new Date(context.store.state.auth.refreshTokenExpiry)
) {
console.info("[MIDDLEWARE] Tokens are expired, logging out...");
context.store.dispatch("auth/logout");
} else if (
context.store.getters["auth/isAuthenticated"] &&
new Date() > new Date(context.store.state.auth.tokenExpiry) &&
new Date() < new Date(context.store.state.auth.refreshTokenExpiry)
) {
console.info("[MIDDLEWARE] Refresh token still valid, refreshing...");
context.store.dispatch("auth/refreshAuth");
}
}
auth/initAuth
initAuth(vuexContext) {
let token = Cookie.get("token");
let tokenExpiry = Cookie.get("tokenExpiry");
let refreshToken = Cookie.get("refreshToken");
let refreshTokenExpiry = Cookie.get("refreshTokenExpiry");
let userId = Cookie.get("userId");
let tokenData = {
userId,
token,
tokenExpiry,
refreshToken,
refreshTokenExpiry
};
//if there is no data to use -> redirect
if (!token || !tokenExpiry || !refreshToken || !refreshTokenExpiry) {
console.info("[AUTH] No cookie files found , redirecting...");
this.$router.replace("/login");
return;
} else if (
refreshTokenExpiry &&
new Date() > new Date(refreshTokenExpiry)
) {
console.info("[AUTH] Tokens too old , logout...");
vuexContext.dispatch("logout");
return;
}
vuexContext.commit("SET", tokenData);
// Adds header: `Authorization: Token token` to all requests
this.$axios.setToken(token, "Token");
}
index.vue
<template>
<div>
<BulmaDashboard/>
</div>
</template>
<script>
import BulmaDashboard from "@/components/SampleContent/BulmaDashboard";
export default {
middleware: "auth",
layout: "section",
fetch({ store, params }) {
store.dispatch("user/getUser")
.then(() => console.log("user action dispatched"));
},
components: {
BulmaDashboard
},
mounted() {
console.log("index mounted!");
}
};
</script>
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
Forgot to close it but it's fixed since alpha release :)