Deno LandDeno

Deploy Docs

Redirect requests

Deploy this example

To redirect a request to our preferred destination, we need to send a response with a header named location containing the destination address and a status code that lies between 300-399. In this post let's take a look at how we can redirect requests in Deno Deploy.

function handleRequest(request) {
  const { pathname } = new URL(request.url);

  if (pathname.startsWith("/deno")) {
    // The long way of doing it.
    // Create an empty response with a header named 'location' containing
    // the destination address and a status code that lies between 300-399.
    return new Response(null, {
      headers: {
        location: "https://deno.land",
      },
      // 302 indicates to the client that the location of this request
      // is found and might change in future so the client should not
      // cache the location.
      status: 302,
    });
  }

  if (pathname.startsWith("/deploy")) {
    // The short way of doing it.
    // Response has a static method that does what's
    // mentioned above but allows us to avoid the boilerplate.
    return Response.redirect("https://deno.com/deploy", 302);
  }
}

addEventListener("fetch", (event) => {
  event.respondWith(handleRequest(event.request));
});

Status codes not only indicate to the client that the response is a redirect but also influence the way the client behaves for future requests. For example, when you send a 301 status code, the client will cache the location and will directly make all future requests to the destination. So it is important to use appropriate status code. You can learn more about them here.


Please file an issue in our feedback repository if you find any problem in Deploy service or documentation.