When you press F5, the login page appears, and then the protected page (middleware auth)
Closed this issue · 2 comments
Environment
- Operating System: Windows_NT
- Node Version: v18.16.0
- Nuxt Version: 3.5.0
- Nitro Version: 2.4.1
- Package Manager: npm@9.6.6
- Builder: vite
- User Config: modules, quasar, auth, http, runtimeConfig
- Runtime Modules: nuxt-quasar-ui@1.7.3, @nuxt-alt/auth@2.5.0, @pinia/nuxt@0.4.10
- Build Modules: -
Nuxt Config
auth: {
strategies: {
local: {
scheme: 'refresh',
localStorage: {
prefix: 'auth.'
},
token: {
prefix: 'access_token.',
property: 'results.access',
maxAge: 60 * 5,
global: true,
},
refreshToken: {
prefix: 'refresh_token.',
property: 'results.refresh',
data: 'refresh',
maxAge: 60 * 60 * 24 * 15
},
user: {
property: 'results.user',
autoFetch: true
},
endpoints: {
login: {url: '/api/token/', method: 'post'},
refresh: {url: '/api/token/refresh/', method: 'post'},
user: {url: '/api/v1/user/', method: 'get'},
logout: {url: '/api/v1/user_logout/', method: 'post'}
},
}
},
routerStrategy: 'navigateTo',
watchLoggedIn: true,
globalMiddleware: true,
pinia: {
persist: true,
},
redirectStrategy: 'query',
redirect: {
login: '/login',
logout: '/',
callback: '/',
home: '/'
}
},
Reproduction
none links
Describe the bug
I have two pages:
/login - Login page
/order - page with middleware auth
When I go to the page "/order", I log in, everything is fine. But if you press F5 on the page "/order", then the page "/login" will load first, and then it will change to the correct one "/order"
I think that the middleware should read cookies and log in when the application initializes on the server side first time (SSR).
Additional context
To solve this problem, I used a server plugin that checks cookies and initializes auth if necessary:
place it to /plugins/init.server.js file
import {defineNuxtPlugin, useRequestHeaders} from '#app';
import { useNuxtApp } from "#imports";
function cookieFromRequestHeaders (key) {
const headers = useRequestHeaders(['cookie']);
if ('cookie' in headers) {
const cookie = headers.cookie.split(';').find(
c => c.trim().startsWith(`${key}=`)
);
if (cookie) {
return decodeURIComponent(cookie.split('=')[1]);
}
}
return '';
}
export default defineNuxtPlugin(async (nuxtApp) => {
const token = cookieFromRequestHeaders('auth.access_token.local');
const refreshtoken = cookieFromRequestHeaders('auth.refresh_token.local');
const ctx = useNuxtApp();
const auth = ctx.$auth;
if (token && token.length > 15 && refreshtoken && refreshtoken.length > 15) {
await auth.setStrategy('local').then(()=>{
auth.setUserToken(token, refreshtoken);
});
}
});
Perhaps something similar can be implemented here
Logs
No response
In my implementation, the names of cookies and strategies are hard-coded. It's for refresh strategy
I do not know, but after upgrade to nuxt 3.5.0 everything became fine.
I tried to repeat it on the previous version, everything works too