How to reroute a request to a different template: GET /hello -> render(/foo/hello.vue)
Hi, when a request comes into the server, I want to check the hostname and decide which page to render.
How can I do that? I've looked at nuxt-multi-tenant module and it's possible, but that module uses dynamic routes. I have static routes.
Seems like this should be an easy win, but when I try to modify event.page in defineEventHandler() it's read-only. π¦ Howto? Thanks!
Seems like this should be an easy win, but when I try to modify event.page in defineEventHandler() it's read-only. π¦ Howto? Thanks!
3 Replies
Hi @FunAndFriendly. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
I understand you want to route requests to different templates based on the hostname. This is indeed possible in Nuxt 3, and there are several approaches you can take.
Using Server Middleware
You can create a server middleware to check the hostname and redirect to the appropriate route:
This middleware will run on every request before any other server route, allowing you to inspect the hostname and redirect as needed.
Using Router Options
You can customize your routes using the router options:
Using the Pages Hook
For more control, you can use the
pages:extend
hook in your Nuxt config:
Using a Server Handler with Request Event
You can also create a server handler to check the hostname and handle the routing:
The getRequestHeader
and sendRedirect
utilities are available from the H3 library that Nuxt uses for its server handling H3 Request Utils and H3 Response Utils.
Remember that you can access the request event in your components using the useRequestEvent
composable, which gives you access to the incoming request useRequestEvent.
These approaches should give you the flexibility to route requests based on hostname without needing to use dynamic routes.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@478253467077574666> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Thanks kapa, but I don't want a redirect. I want to render a different template.