Posted
2 months ago

301 redirects + web server

I have a large list of 301 redirects. How can I implement these 301 redirects in AdonisJS? This list is maintained outside of AdonisJS in different system. I can fetch the list using API, so if the list is changed, how to update the redirects in AdonisJS without editing any code? What web server in fact does AdonisJS use in the core?

Join The Discussion! (1 Replies)

Please sign in or sign up for free to join in on the dicussion.

  1. Commented 2 months ago

    Hi Miro! If I'm following correctly, depending on the desired behavior this could be set up as either a catch-all route or a middleware, something similar to the below should do. Also, AdonisJS uses good ol' NodeJS under the hood node:http.

    Catch All Route

    Use a catch-all route when the redirects should not overwrite any of your defined AdonisJS routes.

    You can add this route to the end of your AdonisJS route definitions that way if none of your application routes match the request, it'll be used.

    // 👆 all other routes
    
    router.get('*', async ({ request, response }) => {
      const url = request.url()
      const redirectTo = 'https://duckduckgo' // 👈 check your api for a redirect
    
      if (!redirectTo) {
        return response.notFound()
      }
    
      return response.redirect(redirectTo)
    })
    Copied!

    Middleware

    You can either create it as an global HTTP or a named middleware.

    • Global HTTP will run on any matched route in your app.

    • Named middleware only runs on the routes you apply the middleware to

    export default class RedirectMiddleware {
      async handle({ request, response }: HttpContext, next: NextFn) {
        const url = request.url()
        const redirectTo = 'https://duckduckgo' // 👈 check your api for a redirect
    
        if (redirectTo) {
          // 👇 stop the request here and redirect 
          return response.redirect(redirectTo)
        }
    
        // 👇 continue with request to other middleware & route handler
        return next()
      }
    }
    Copied!

    You can also optionally cache your API responses as you see fit as well so you don't have to relay back to it with every request.

    Hope this helps!

    0

    Please sign in or sign up for free to reply