Search code examples
clojurecompojure

Serve index.html at / by default in Compojure


I have a static file called index.html that I'd like to serve when someone requests /. Usually web servers do this by default, but Compojure doesn't. How can I make Compojure serve index.html when someone requests /?

Here's the code I'm using for the static directory:

; match anything in the static dir at resources/public
(route/resources "/")

Solution

  • This would be a pretty simple Ring middleware:

    (defn wrap-dir-index [handler]
      (fn [req]
        (handler
         (update-in req [:uri]
                    #(if (= "/" %) "/index.html" %)))))
    

    Just wrap your routes with this function, and requests for / get transformed into requests for /index.html before the rest of your code sees them.

    (def app (-> (routes (your-dynamic-routes)
                         (resources "/"))
                 (...other wrappers...)
                 (wrap-dir-index)))