Redirect in Haskell Servant

by||2 min read
Haskell Servant Redirect
Haskell Servant Redirect

Sometimes we are faced with redirects in our web applications. Let's explore in this article how this can be achieved in Servant.

As for my professional work I use PHP and JavaScript (more OO programming languages), my expectation was to return a specific Response in my Handler code. For instance, I recently released an application (Currency Converter NEO). I wanted to show a Landingpage for the tool and redirect directly to the Google Chrome Webstore if the application is installable on the device (Chrome Web Browser).

Let's take PHP as an example here. In the Symfony Framework it would look something like this:

public function indexAction()
{
    return $this->redirect('http://stackoverflow.com');
    // return $this->redirect('http://stackoverflow.com', 301); - for changing HTTP status code from 302 Found to 301 Moved Permanently
}

As you can see we are returning a well pre-defined response with the URL of the target destination. In Servant this does not work exactly the same way. We need to put a bit more effort and understand how redirects work in general. Symfony is hiding this kind of information from the developer to make development easier and more readable. On the other hand, we tend to loose basic skills of the underlying technologies.

So, here is the example in Servant:

handlerWithRedirect :: AppT m SomePage
handlerWithRedirect = do
  throwErr err301 { errHeaders = [("Location", "https://stackoverflow.com")] }

As you can see, we can not just "return" a normal response since in Haskell world we thrive towards types and their strictness. We need to return "SomePage" data, there is "no way around it". The only possibility to escape here is via an error. We make use of throwErr and modify the default err301 from Servant to set the proper Location header. In fact, this is how a redirect is done behind the scenes.

Thank you for reading this far! Let’s connect. You can @ me on Twitter (@debilofant) with comments, or feel free to follow. Please like/share this article so that it reaches others as well.

© Copyright 2022 - Ersocon - All rights reservedVer. 2.3.6.4