Reputation: 253
I'm working on a universal Nuxt app that uses the standard Django session authentication. I need to restrict some pages in my project to logged in users only, so i decided to use a middleware.
The problem with the middleware is that it will run from server side, so it will always return False
to the user even when the user is logged in, since it doesn't send any cookie in the request. This happens only when i refresh page or when i navigate directly to it, not when i navigate from another page to a restricted page, that's because in that case the middleware is executed client side and not server side.
Is there any way i can "force" the following code to run client side instead of server side from the middleware? Or do i have to look for another solution?
export default async function (context) {
axios.defaults.withCredentials = true;
return axios({
method: 'get',
url: 'http://127.0.0.1:8000/checkAuth',
withCredentials: true,
}).then(function (response) {
//Check if user is authenticated - response is always False
}).catch(function (error) {
//Handle error
});
}
I tried to do the same with nuxtServerInit
but the outcome is the same. If i run that code in the beforeCreate
block from the page it will first load the page and then execute the request, which works but it's quite ugly since the user will see the page for a second before being redirected.
Upvotes: 5
Views: 5462
Reputation: 478
There is another way around this. First You need to run your middleware code only on the client side.
export default async function (context) {
if(process.client) {
// your middleware code here
}
}
Now you just have to take care of the first load of your application. you can create a plugin that only runs on the client-side and use the middleware code inside the plugin. for running the plugin only on the client use the mode key word like this. this is the nuxt.config.js:
plugins: [
{ src: '~/plugins/client-only.js', mode: 'client' }, // only on client side
]
Upvotes: 6