#Render page from server route

1 messages · Page 1 of 1 (latest)

devout nest
#

Disclaimer: I realize the title might indicate an XY problem, so that's why I've given the full context. If there's a better approach, I'm 100% open to that 🙂

Context: I'm making a link shortener/aggregator. It has a single page, which fetches and display existing links, and three server routes: links.post.ts, that creates links, links.get.ts, that lists all the links, and links/[link].get.ts, that redirects the user to the long URL of that link.

Problem: I want to handle my-website.com with the index page, but my-website.com/link with the API function.

Attempted solutions:

  • Using a server route at server/routes/[link].get.ts makes it so I can't display the home page anymore
  • Using a custom route in app/router.config.ts tries to render a /link page, which does not exist. Plus, it's a client redirect AFAIK and I'd like to have a server-side redirect

The last thing I could think of is some way of rendering the home page from the server route, but I didn't find how to do it, or if that's even possible.
Am I missing something or this setup just can't work?

limpid wagon
#

I solved a similar challenge by using server middleware. I listened for the incoming request path and altered the response accordingly.

export default defineEventHandler((event) => {
  const hash = getRequestPath(event).match(
    /^\/(?<hash>ai-[a-z0-9]+)/i
  )?.groups?.hash;

  if( hash ) {
     return sendRedirect(event, REDIRECT-TO-URL, 307); // <- I haven't tested it
  }
});
devout nest
#

It worked! Thank you so much! ❤️