nuxt 3 global middleware for redirecting
I am trying to implement a middleware which will run always in case if someone is trying to hit a /app route. Middleware should make auto redirect to /app/chat. Also i have a localization made by @nuxtjs/i18n which save locale code to cookie and then use it.
I implemented like that
import { useRouter } from "vue-router";
export default defineNuxtRouteMiddleware((to, from) => {
const router = useRouter();
const localePath = useLocalePath();
if (to.path === "/app") {
console.log("Redirecting to /app/chat");
return router.push(localePath("/app/chat"));
}
});
Whole path will look like localhost:3000/cs/app -> localhost:3000/cs/app/chat
But looks like my middleware is not working, because i dont even see logs in my console
20 Replies
What happens when you just put a console log in middleware without anything else?
Also why do you have import?
without logic and just console logging i am getting logs. I made import just to make sure that logic will use correctly 😄
so problem is somewhere in a logic of middleware
And when you add an else?
else block is working, so i am getting "Skipping redirect to /app"
Why happens when you log to.path in else
because to.path === "/app" is not catching in if statement 😄
i was thinking if problem can be in localization, but "cs/app" didnt work
even to.path.startsWith("cs/app/") not catching
Bro. I am trying to help. Please log to.path in else and tell me what result is
sry, here is the answer: /cs/app/
So than you have to use /cs/app - or whatever page you want to redirect …
now i can see the problem. When i entered /cs/app/ it works, but problem now is:
i go to /cs/app/ it redirects me to /cs/app/chat, but i can still see 404 because i dont have page for cs/app/. Z have to go to url and press enter again so i get my page chat on a screen
Are you using file base routing? Or a custom router config.
file base routing. pages -> app (later it will contain different pages based on app function) -> chat -> idnex.vue
Ok so if you don’t have the page how can it show it?
i were expecting it will automaticaly skip that to chat without even loading a apge
I think it will be best to make a reproduction so we can assist easily 😄
Nope you would have to make a custom router config to do that or create the correct dir structure
i think it would be better to make a new dir structure, I don't want to burden you 😃 . Thank you very much for help and clarifying how nuxt works
👍
Repro always welcome though.
Thank you. In case if i spend more time on it, i will catch you in DM
FYI having a page who’s
definePageMeta
contains a redirect does not translate to “load this page and redirect” because it’s a macro, it is extrapolated and added to the router config as a redirect.
File based routing is not like having html files in a directory, if that is all you think is happening.Thank you very much for info, my friend. I will keep it in mind 👍