This content originally appeared on Modern Web Development with Chrome and was authored by Paul Kinlan
<p>I run a static site, it's built with Hugo and hosted on the edge with Vercel. Sometimes, I just want to include a small piece of server-side logic (Copyright notice anyone?) without having to spin up a complex node server or api endpoints. Sometimes I want to be able to drop a small piece of dynamic content in one single page on my static site.</p>
<p>That's what I loved about Apache mod_include. <code>mod_include</code> let's you drop a specially formatted HTML comment in to your HTML template and Apache server would then 'include' the output of the command in your outputted HTML. e.g,<code><!--#include file="test.txt" --></code> which will include the content of a file where the include is and <code><!--#include virtual="/api/time.js" --></code> would call a function and return the output in place of the include.</p>
<p>But how do you get it working for sites hosted with Vercel?</p>
<p>I wrote a little <a href="https://github.com/PaulKinlan/vercel-ssi">function</a> (<a href="https://ssi.vercel.app/">demo</a> - note you can see a file included and also a function call) that you can use to simulate <code>mod_include</code>.</p>
<p>Vercel has a <a href="https://github.com/PaulKinlan/vercel-ssi/blob/master/vercel.json#L3">request router that is configured</a> to rewrite <em>all</em> requests for html pages so that they pass through the <a href="https://github.com/PaulKinlan/vercel-ssi/blob/master/api/ssi.js">ssi.js</a> function which in turn will parse the requested html file looking for the includes to replace.</p>
<p>The implementation of <code>file</code> command (<a href="https://ssi.vercel.app/file.html">demo</a>) is relatively straight forward using simple <code>fs</code> functions to inject content into a page. The <code>virtual</code> command (<a href="https://ssi.vercel.app/virtual.html">demo</a>) is more interesting because I didn't want to spin up a <code>vm</code> in node to execute a function so instead the handler uses <code>http-fetch</code> to call the file in /api directory. /api/ is the new /cgi-bin/ - I'm certainly open to suggestions if <code>vm</code> is a better solution, because the <code>node-fetch</code> certainly adds some extra latency.</p>
<p>You will want to make sure caching is properly enabled because you really don't want to have to execute functions for every single page-view, you still want to get your 'static' pages cached on the edge.</p>
<p>I'm unsure if you should use this in production, I would love Vercel to offer something similar to cloudflare's workers and <a href="https://developers.cloudflare.com/workers/reference/apis/html-rewriter/">HTMLRewriter</a> that allow you to manipulate static files (or function response) before it's sent to the client.</p>
This content originally appeared on Modern Web Development with Chrome and was authored by Paul Kinlan