{"id":12537,"date":"2015-09-17T01:00:00","date_gmt":"2015-09-17T00:00:00","guid":{"rendered":"http:\/\/pjagielski.github.com\/2015\/09\/17\/clojure-web-dev-state"},"modified":"2022-08-03T09:02:58","modified_gmt":"2022-08-03T07:02:58","slug":"clojure-web-development-state-of-the-art","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2015\/09\/17\/clojure-web-development-state-of-the-art\/","title":{"rendered":"Clojure web development &#8211; state of the art"},"content":{"rendered":"<p>It\u2019s now more than a year that I\u2019m getting familiar with Clojure and the more I dive into it, the more it becomes <strong>the language<\/strong>. Once you defeat the \u201cparentheses fear\u201d, everything else just makes the difference: tooling, community, good engineering practices. So it\u2019s now time for me to convince others. In this post I\u2019ll try to walktrough a simple web application from scratch to show key tools and libraries used to develop with Clojure in late 2015.<\/p>\n<p><strong>Note for Clojurians<\/strong>: This material is rather elementary and may be useful for you if you already know Clojure a bit but never did anything bigger than hello world application.<\/p>\n<p><strong>Note for Java developers<\/strong>: This material shows how to replace Spring, Angular, grunt, live-reload with a bunch of Clojure tools and libraries and a bit of code.<\/p>\n<p>The repo with final code and individual steps is <a href=\"https:\/\/github.com\/pjagielski\/modern-clj-web\">here<\/a>.<\/p>\n<h2 id=\"bootstrap\">Bootstrap<\/h2>\n<p>I think all agreed that <a href=\"https:\/\/github.com\/stuartsierra\/component\">component<\/a> is the industry standard for managing lifecycle of Clojure applications. If you are a Java developer you may think of it as a Spring (DI) replacement &#8211; you declare dependencies between \u201ccomponents\u201d which are resolved on \u201csystem\u201d startup. So you just say \u201cmy component needs a repository\/database pool\u201d and component library \u201cinjects\u201d it for you.<\/p>\n<p>To keep things simple I like to start with <a href=\"https:\/\/github.com\/weavejester\/duct\">duct<\/a> web app template. It\u2019s a nice starter component application following the <a href=\"http:\/\/12factor.net\/\">12-factor<\/a> philosophy. So let\u2019s start with it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">lein new duct clojure-web-app +example<\/pre>\n<p>The <code>+example<\/code> parameter tells duct to create an example endpoint with HTTP routes &#8211; this would be helpful. To finish bootstraping run <code>lein setup<\/code> inside <code>clojure-web-app<\/code> directory.<\/p>\n<p>Ok, let\u2019s dive into the code. Component and injection related code should be in <code>system.clj<\/code> file:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">(defn new-system [config] (let [config (meta-merge base-config config)] (-&gt; (component\/system-map :app (handler-component (:app config)) :http (jetty-server (:http config)) :example (endpoint-component example-endpoint)) (component\/system-using {:http [:app] :app [:example] :example []}))))<\/pre>\n<p>&nbsp;<\/p>\n<\/div>\n<p>In the first section you instantiate components without dependencies, which are resolved in the second section. So in this example, \u201chttp\u201d component (server) requires \u201capp\u201d (application abstraction), which in turn is injected with \u201cexample\u201d (actual routes). If your component needs others, you just can get then by names (precisely: by Clojure keywords).<\/p>\n<p>To start the system you must fire a REPL &#8211; interactive environment running within context of your application:<\/p>\n<p><code>lein repl<\/code><\/p>\n<p>After seeing prompt type <code>(go)<\/code>. Application should start, you can visit <a href=\"http:\/\/localhost:3000\/\">http:\/\/localhost:3000<\/a> to see some example page.<\/p>\n<p>A huge benefit of using component approach is that you get fully reloadable application. When you change <strong>literally anything<\/strong> &#8211; configuration, endpoints, implementation, you can just type <code>(reset)<\/code> in REPL and your application is up-to-date with the code. It\u2019s a feature of the language, no JRebel, Spring-reloaded needed.<\/p>\n<h2 id=\"adding-rest-endpoint\">Adding REST endpoint<\/h2>\n<p>Ok, in the next step let\u2019s add some basic REST endpoint returning JSON. We need to add 2 dependencies in <code>project.clj<\/code> file:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">:dependencies ... [ring\/ring-json \"0.3.1\"] [cheshire \"5.1.1\"]<\/pre>\n<\/div>\n<p><a href=\"https:\/\/github.com\/ring-clojure\/ring-json\">Ring-json<\/a> adds support for JSON for your routes (in ring it\u2019s called middleware) and <a href=\"https:\/\/github.com\/dakrone\/cheshire\">cheshire<\/a> is Clojure JSON parser (like Jackson in Java). Modifying project dependencies if one of the few tasks that require restarting the REPL, so hit CTRL-C and type <code>lein repl<\/code> again.<\/p>\n<p>To configure JSON middleware we have to add <code>wrap-json-body<\/code> and <code>wrap-json-response<\/code> just before <code>wrap-defaults<\/code> in <code>system.clj<\/code>:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">(:require ... [ring.middleware.json :refer [wrap-json-body wrap-json-response]]) (def base-config {:app {:middleware [[wrap-not-found :not-found] [wrap-json-body {:keywords? true}] [wrap-json-response] [wrap-defaults :defaults]]<\/pre>\n<\/div>\n<p>And finally, in <code>endpoint\/example.clj<\/code> we must add some route with JSON response:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">(:require ... [ring.util.response :refer [response]])) (defn example-endpoint [config] (routes (GET \"\/hello\" [] (response {:hello \"world\"})) ...<\/pre>\n<\/div>\n<p>Reload app with <code>(reset)<\/code> in REPL and test new route with <code>curl<\/code>:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">curl -v http:\/\/localhost:3000\/hello &lt; HTTP\/1.1 200 OK &lt; Date: Tue, 15 Sep 2015 21:17:37 GMT &lt; Content-Type: application\/json; charset=utf-8 &lt; Set-Cookie: ring-session=37c337fb-6bbc-4e65-a060-1997718d03e0;Path=\/;HttpOnly &lt; X-XSS-Protection: 1; mode=block &lt; X-Frame-Options: SAMEORIGIN &lt; X-Content-Type-Options: nosniff &lt; Content-Length: 151 * Server Jetty(9.2.10.v20150310) is not blacklisted &lt; Server: Jetty(9.2.10.v20150310) &lt; * Connection #0 to host localhost left intact {\"hello\": \"world\"}<\/pre>\n<\/div>\n<p>It works! In case of any problems you can find working version in <a href=\"https:\/\/github.com\/pjagielski\/modern-clj-web\/commit\/c15f3c51855034a1c8f8431171134f6719cadffe\">this commit<\/a>.<\/p>\n<h2 id=\"adding-frontend-with-figwheel\">Adding frontend with figwheel<\/h2>\n<p>Coding backend in Clojure is great, but what about the frontend? As you may already know, Clojure could be compiled not only to JVM bytecode, but also to Javascript. This may sound familiar if you used e.g. Coffeescript. But ClojureScript philosophy is not only to provide some syntax sugar, but improve your development cycle with great tooling and fully interactive development. Let\u2019s see how to achieve it.<\/p>\n<p>The best way to introduce ClojureScript to a project is <a href=\"https:\/\/github.com\/bhauman\/lein-figwheel\">figweel<\/a>. First let\u2019s add fighweel plugin and configuration to <code>project.clj<\/code>:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">:plugins ... [lein-figwheel \"0.3.9\"]<\/pre>\n<\/div>\n<p>And cljsbuild configuration:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">:cljsbuild {:builds [{:id \"dev\" :source-paths [\"src-cljs\"] :figwheel true :compiler {:main \"clojure-web-app.core\" :asset-path \"js\/out\" :output-to \"resources\/public\/js\/clojure-web-app.js\" :output-dir \"resources\/public\/js\/out\"}}]}<\/pre>\n<\/div>\n<p>In short this tells ClojureScript compiler to take sources from <code>src-cljs<\/code> with <code>figweel<\/code> support and put resulting JavaScript into <code>resources\/public\/js\/clojure-web-app.js<\/code> file. So we need to include this file in a simple HTML page:<\/p>\n<div class=\"highlight\"><\/div>\n<p>To serve this static file we need to change some defaults and add corresponding route. In <code>system.clj<\/code> change <code>api-defaults<\/code> to <code>site-defaults<\/code> both in require section and <code>base-config<\/code> function. In <code>example.clj<\/code> add following route:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">(GET \"\/\" [] (io\/resource \"public\/index.html\"))<\/pre>\n<\/div>\n<p>Again <code>(reset)<\/code> in REPL window should reload everything.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">id=\"main\"&gt;<\/pre>\n<p>But where is our ClojureScript source file? Let\u2019s create file <code>core.cljs<\/code> in <code>src-cljs\/clojure-web-app<\/code> directory:<\/p>\n<div class=\"highlight\">\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">(ns ^:figwheel-always clojure-web-app.core) (enable-console-print!) (println \"hello from clojurescript\")<\/pre>\n<\/div>\n<p>Open another terminal and run <code>lein figwheel<\/code>. It should compile ClojureScript and print \u2018Prompt will show when figwheel connects to your application\u2019. Open <code>http:\/\/localhost:3000<\/code>. Fighweel window should prompt:To quit,\u00a0<span class=\"nb\">type<\/span>: :cljs\/quit cljs.user<span class=\"o\">=<\/span>&gt;<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">To quit, type: :cljs\/quit cljs.user=&gt;<\/pre>\n<div class=\"highlight\"><\/div>\n<p>Type <code>(js\/alert \"hello\")<\/code>. Boom! If everything worked you should see and alert in your browser. Open developers console in your browser. You should see <code>hello from clojurescript<\/code> printed on the console. Change it in <code>core.cljs<\/code> to <code>(println \"fighweel rocks\")<\/code> and save the file. Without reloading the page your should see updated message. Fighweel rocks! Again, in case of any problems, refer to <a href=\"https:\/\/github.com\/pjagielski\/modern-clj-web\/commit\/8649a5aa137ec15b40dfd8d47c514e5bfe8449ee\">this commit<\/a>.<\/p>\n<p><strong>UPDATE:<\/strong> In the latest <a href=\"https:\/\/github.com\/weavejester\/duct\">duct<\/a> release, there is an <code>+cljs<\/code> option which make it possible to use reloaded repl and fighweel in a single REPL. Highly recommended!<\/p>\n<p>In the next post I\u2019ll show how to fetch data from MongoDB, serve it with REST to the browser and write ReactJs\/Om components to render it. Stay tuned!<\/p>\n","protected":false},"excerpt":{"rendered":"It&rsquo;s now more than a year that I&rsquo;m getting familiar with Clojure and the more I dive into it, the more it becomes the language. Once you defeat the &ldquo;parentheses fear&rdquo;, everything else just makes the difference: tooling, community, good engineering practices. So it&rsquo;s now time for me to convince others. In this post I&rsquo;ll try to walktrough a simple web application from scratch to show key tools and libraries used to develop with Clojure in late 2015. \nNote for Clojurians: This material is rather elementary and may be useful for you if you already know Clojure a bit but never did anything bigger than hello world application. \nNote for Java developers: This material shows how to replace Spring, Angular, grunt, live-reload with a bunch of Clojure tools and libraries and a bit of code.\nThe repo with final code and individual steps is here.\nBootstrap\nI think all agreed that component is the industry standard for managing lifecycle of Clojure applications. If you are a Java developer you may think of it as a Spring (DI) replacement &#8211; you declare dependencies between &ldquo;components&rdquo; which are resolved on &ldquo;system&rdquo; startup. So you just say &ldquo;my component needs a repository\/database pool&rdquo; and component library &ldquo;injects&rdquo; it for you. \nTo keep things simple I like to start with duct web app template. It&rsquo;s a nice starter component application following the 12-factor philosophy. So let&rsquo;s start with it:\nlein new duct clojure-web-app +example\nThe +example parameter tells duct to create an example endpoint with HTTP routes &#8211; this would be helpful. To finish bootstraping run lein setup inside clojure-web-app directory.\nOk, let&rsquo;s dive into the code. Component and injection related code should be in system.clj file:\n\n(defn new-system [config]\r\n  (let [config (meta-merge base-config config)]\r\n    (-&gt; (component\/system-map\r\n         :app  (handler-component (:app config))\r\n         :http (jetty-server (:http config))\r\n         :example (endpoint-component example-endpoint))\r\n        (component\/system-using\r\n         {:http [:app]\r\n          :app  [:example]\r\n          :example []}))))\n\nIn the first section you instantiate components without dependencies, which are resolved in the second section. So in this example, &ldquo;http&rdquo; component (server) requires &ldquo;app&rdquo; (application abstraction), which in turn is injected with &ldquo;example&rdquo; (actual routes). If your component needs others, you just can get then by names (precisely: by Clojure keywords).\nTo start the system you must fire a REPL &#8211; interactive environment running within context of your application:\nlein repl\nAfter seeing prompt type (go). Application should start, you can visit http:\/\/localhost:3000 to see some example page.\nA huge benefit of using component approach is that you get fully reloadable application. When you change literally anything &#8211; configuration, endpoints, implementation, you can just type (reset) in REPL and your application is up-to-date with the code. It&rsquo;s a feature of the language, no JRebel, Spring-reloaded needed.\nAdding REST endpoint\nOk, in the next step let&rsquo;s add some basic REST endpoint returning JSON. We need to add 2 dependencies in project.clj file:\n\n:dependencies\r\n ...\r\n  [ring\/ring-json \"0.3.1\"]\r\n  [cheshire \"5.1.1\"]\n\nRing-json adds support for JSON for your routes (in ring it&rsquo;s called middleware) and cheshire is Clojure JSON parser (like Jackson in Java). Modifying project dependencies if one of the few tasks that require restarting the REPL, so hit CTRL-C and type lein repl again.\nTo configure JSON middleware we have to add wrap-json-body and wrap-json-response just before wrap-defaults in system.clj:\n\n(:require \r\n ...\r\n [ring.middleware.json :refer [wrap-json-body wrap-json-response]])\r\n\r\n(def base-config\r\n   {:app {:middleware [[wrap-not-found :not-found]\r\n                      [wrap-json-body {:keywords? true}]\r\n                      [wrap-json-response]\r\n                      [wrap-defaults :defaults]]\n\nAnd finally, in endpoint\/example.clj we must add some route with JSON response:\n\n(:require \r\n ...\r\n [ring.util.response :refer [response]]))\r\n\r\n(defn example-endpoint [config]\r\n  (routes\r\n    (GET \"\/hello\" [] (response {:hello \"world\"}))\r\n    ...\n\nReload app with (reset) in REPL and test new route with curl:\n\ncurl -v http:\/\/localhost:3000\/hello\r\n\r\n&lt; HTTP\/1.1 200 OK\r\n&lt; Date: Tue, 15 Sep 2015 21:17:37 GMT\r\n&lt; Content-Type: application\/json; charset=utf-8\r\n&lt; Set-Cookie: ring-session=37c337fb-6bbc-4e65-a060-1997718d03e0;Path=\/;HttpOnly\r\n&lt; X-XSS-Protection: 1; mode=block\r\n&lt; X-Frame-Options: SAMEORIGIN\r\n&lt; X-Content-Type-Options: nosniff\r\n&lt; Content-Length: 151\r\n* Server Jetty(9.2.10.v20150310) is not blacklisted\r\n&lt; Server: Jetty(9.2.10.v20150310)\r\n&lt;\r\n* Connection #0 to host localhost left intact\r\n{\"hello\": \"world\"}\n\nIt works! In case of any problems you can find working version in this commit.\nAdding frontend with figwheel\nCoding backend in Clojure is great, but what about the frontend? As you may already know, Clojure could be compiled not only to JVM bytecode, but also to Javascript. This may sound familiar if you used e.g. Coffescript. But ClojureScript philosophy is not only to provide some syntax sugar, but improve your development cycle with great tooling and fully interactive development. Let&rsquo;s see how to achieve it.\nThe best way to introduce ClojureScript to a project is figweel. First let&rsquo;s add fighweel plugin and configuration to project.clj:\n\n:plugins\r\n   ...\r\n   [lein-figwheel \"0.3.9\"]\n\nAnd cljsbuild configuration:\n\n:cljsbuild\r\n    {:builds [{:id \"dev\"\r\n               :source-paths [\"src-cljs\"]\r\n               :figwheel true\r\n               :compiler {:main       \"clojure-web-app.core\"\r\n                          :asset-path \"js\/out\"\r\n                          :output-to  \"resources\/public\/js\/clojure-web-app.js\"\r\n                          :output-dir \"resources\/public\/js\/out\"}}]}\n\nIn short this tells ClojureScript compiler to take sources from src-cljs with figweel support and but resulting JavaScript into resources\/public\/js\/clojure-web-app.js file. So we need to include this file in a simple HTML page:\n\n&lt;!DOCTYPE html&gt;\r\n&lt;head&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n  &lt;div id=\"main\"&gt;\r\n  &lt;\/div&gt;\r\n  &lt;script src=\"js\/clojure-web-app.js\" type=\"text\/javascript\"&gt;&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\n\nTo serve this static file we need to change some defaults and add corresponding route. In system.clj change api-defaults to site-defaults both in require section and base-config function. In example.clj add following route:\n\n(GET \"\/\" [] (io\/resource \"public\/index.html\")\n\nAgain (reset) in REPL window should reload everything.\nBut where is our ClojureScript source file? Let&rsquo;s create file core.cljs in src-cljs\/clojure-web-app directory:\n\n(ns ^:figwheel-always clojure-web-app.core)\r\n\r\n(enable-console-print!)\r\n\r\n(println \"hello from clojurescript\")\n\nOpen another terminal and run lein fighweel. It should compile ClojureScript and print &lsquo;Prompt will show when figwheel connects to your application&rsquo;. Open http:\/\/localhost:3000. Fighweel window should prompt:\n\nTo quit, type: :cljs\/quit\r\ncljs.user=&gt;\n\nType (js\/alert \"hello\"). Boom! If everything worked you should see and alert in your browser. Open developers console in your browser. You should see hello from clojurescript printed on the console. Change it in core.cljs to (println \"fighweel rocks\") and save the file. Without reloading the page your should see updated message. Figweel rocks! Again, in case of any problems, refer to this commit.\nIn the next post I&rsquo;ll show how to fetch data from MongoDB, serve it with REST to the broser and write ReactJs\/Om components to render it. Stay tuned! \n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[594,491,71,402],"class_list":{"0":"post-12537","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design","7":"tag-api","8":"tag-clojure","9":"tag-frontend","10":"tag-rest"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12537","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=12537"}],"version-history":[{"count":16,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12537\/revisions"}],"predecessor-version":[{"id":14888,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12537\/revisions\/14888"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=12537"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=12537"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=12537"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}