David.dev 🎪

about ~ apps

2019-10-23 #nodejs

Polka: an express.js alternative

This is my short review of Polka which is "... just a native HTTP server with added support for routing, middleware, and sub-applications...!"  even if express is fairly light, polka is even lighter. What I found interesting about this framework is giving you even more insight about how to build an application.

Much of the functionality is explained in the docs so I won't repeat what you can find in the examples but I will add some information about what you miss to write a fully fledged CRUD app.

First you need templating. The only plugin I could find written specifically for Polka is polka ejs that allows you to use ejs templates. You can probably include or use other modules but I found this to be very straightforward:

const ejs = require("polka-ejs");
app.use(ejs()); // load ejs for templating 
var hello = "hello world";
app.get("hello", auth.connect(basic), (req, res) => {
res.render("hello.ejs", {hello: hello
});
});

Another two libraries that you would need for web development are serve-static to server public directory files (e.g. css files) and body parser to easily parse parameters from forms: 

const {join} = require('path'); //static server
const polka = require("polka");
const ejs = require("polka-ejs");
const dir = join(__dirname, 'public'); //dir for public
const serve = require('serve-static')(dir); //serve static is needed to serve static files
const app = polka();
var bodyParser = require('body-parser');

so with body-parser, polka-ejs, serve-static we can now server public files, parse and serve pages using ejs templates:

app.use(ejs()); // load ejs for templating 
app.use('/public', serve); // loading public folder
app.use(bodyParser.urlencoded({ //load bodyparser for POST parameters
extended: true
}));

all we need now for a fully fledged CMS is a database like mysql, mongo or even the very light and useful lowdb. 

Another cool feature is the possibility to use the main "/" route for both articles and the index, and other areas of site. You do not need to add a conditional to achieve that you just have to first add your index route

app.get('/', (req, res) => {
 res.render("index.ejs", {
results: results
}); // get db results for index here... 

and then the dynamic route at the end of your routes

app.get(':id', (req, res) => {
var id = req.params.id;
.....
});

I think that Polka is an excellent alternative to express. With few extra libraries you will have a fully fledged framework with robust routes, templating, static files serving so everything you have in express in a more compact (and probably faster)package. It doesn't have the same adoption as express but that is perhaps an advantage. The syntax is very similar so if you know express you probably know Polka. If you don't know express, you can always learn it after polka!