Template: header
Template: markdown
Server middleware
The Amagaki server can be extended with Express middleware. This may be useful
in a variety of scenarios, such as:
- Enforcing authentication flows, i.e. for headless CMS or content integrations
- Adding headers or metadata to the HTTP responses, i.e. for testing production
behavior - Extending the functionality of Amagaki with custom request handlers
Remember, Amagaki is intended to be a static site generator. Request handlers
made available on the server will not be available in production when serving a
fully static site. Therefore, server middleware is most useful for adding
functionality that enhances development velocity and the development workflow.
Examples
export default (pod: Pod) => {
const serverPlugin = pod.plugins.get('ServerPlugin') as ServerPlugin;
<span class="hljs-comment">// Immediate example. Use for registering Express middleware.</span>
serverPlugin.register(<span class="hljs-function"><span class="hljs-params">app</span> =></span> {
app.use(<span class="hljs-string">'/foo'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =></span> {
res.send(<span class="hljs-string">'This is a response from custom middleware.'</span>);
});
});
<span class="hljs-comment">// Async example. Use for running some task prior to server startup.</span>
serverPlugin.register(<span class="hljs-keyword">async</span> () => {
<span class="hljs-keyword">const</span> promise = <span class="hljs-function">() =></span> {
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span><<span class="hljs-built_in">void</span>>(<span class="hljs-function"><span class="hljs-params">resolve</span> =></span> {
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =></span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'tested'</span>);
resolve();
}, <span class="hljs-number">2000</span>);
});
};
<span class="hljs-keyword">await</span> promise();
});
}
Template: footer