Target audience: familiar with Javascript, familiar with HTTP requests/responses, beginner with NodeJS and Express. We are going to to introduce Express to beginners who want to write a site or API with it and solve a common problem as a break in point.
Super quick refresher:
NodeJS: Enables you run Javascript on the server. As easy as:
$ echo "console.log('hello world');" | node |
$ hello world
|
ExpressJS: NodeJS has a built in HTTP Server library which can be used in as easy as three lines of code. Express augments the HTTP server which makes it easier to handle complex tasks such as routing, view rendering, error handling, and much more. Their documentation is very informative. Here are links to Getting Started and the Guide which I found to be great and very informative.
Purpose:
When I started out with Express my goal was to build a fully functioning website as I had done with ASP.NET MVC in the past. During my project I have probed the minds of people far more experienced than I, and scoured the deep edges of the web for those “best practices”. I want to share with you what I have learned in hopes I can answer a few common questions I had when I was first starting. If you’re reading this and it has been over a year since the last edit, stop reading and don’t waste your time. Modern Javascript development eh? ¯\_(ツ)_/¯
Important things to know about Express.
Middleware: A function that can run before, or after a handle somewhere in the chain. Say for instance if you want the same function to run on every single request to your app. Or ONLY before requests to /customer (/customer/new /customer/1/edit) or ONLY when no handlers matched the route (404) or ONLY when there is an error thrown in a handler. Okay, you probably get the point.
The real takeaway here is that ExpressJS has hundreds of middle-ware that other users and the express team have created that you can drop into your application. Most common functionality like a session system have been broken off into a different module that you have to install. This is the node way. It is why I love node, and why some don’t. Keep all of this in the back of your mind, chances are if you are writing the same, or similar code in every router you are doing it incorrectly and you now need to move that code to its own middleware. See router.param.
Stop your nonsensical babbling and give me some code!
Okay! Try and keep up!
Lets grab the hello world code straight off of the express hello world example:
var express = require('express'); var app = express(); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); }); |
What’s nice about the code here is that the API is easy to read. app.get(‘/’, callback) will run on any HTTP GET request to /. Like typing this into your browser http://localhost:3000/. However, http://localhost:3000/customer would NOT fire that handler.
Also notice the req and res parameters. req has all the request data. If you put middleware somewhere above that handler you would be able to attach all sorts of data to the req like a database access object (DAO), or your config object. This is a secure, logical spot because the req has already been received, data attached to it for the use of processing it makes sense, and none of it gets sent back to the user (unless it is attached to session which we will cover later)
The session:
I needed to know how to set a session. I had to know where to store the users information after I verified they were logged in. Enter, express-session. Install with NPM (npm install express-session) To use this it must be initialized and attached to the app as middleware.
var sess = { secret: process.env.SESSION_SECRET, cookie: {}, saveUninitialized: false, resave: false } app.use(session(sess)); |
Make sure to define var session as
var session = require('express-session'); |
at the top of your app.
Some important notes: The secret is used to encrypt the session ID, session data is stored server side always, the ID is how its matched up. You need to export the environment variable SESSION_SECRET. There are many ways to store secret keys on a server. Read how Amazon recommends it.
I highly recommended that you read the documentation for express-session. It has very important points about the options I am using above like saveUninitialized and resave.
It also discusses how to handle https and trust proxies which you should really use when moving to production. Google “ExpressJS nginx” when moving to production. Focus on setting NGINX to handle the SSL termination, and handle serving static files as well as caching.
It is also recommended to use a different session store instead of the memory session. I prefer using Redis. Redis fast and easy to plug right into express-session.
Storing data:
This is as easy as changing req.session on any handler. You simply add data to it like req.session.user = getUserFromDatabase(“john@example.com”);
A sample login handler:
app.get('/login', function (req, res) { req.session.user = req.query.email; res.redirect("/"); }); |
When the user hits /login?email=john@example.com the user is set! In a real setting you would have a form POST to login, and the credentials would be verified against a database, or you would use OAuth.
More reading (I could and might write entire posts on each of these):
- Use express-promise-router to handle your routing. It makes error handling so much easier. The creator, Joe is really helpful and talented programmer, see his info on express-promise-router here.
- Tokens for when you want to create “API Keys” with JWT. (I have personally used JWT to create a token for those “confirm your email” links after people register).
- Nunjucks: my favorite view engine (handlebars is also really nice).
- Free SSL certs!
- While doing research for my post I stumbled upon this cool tutorial Using Sessions and HttpContext in ASP.NET 5 and MVC6
- Fun facts: There are 20 anchor tags in this post.
This post was originally published on the Computer Services blog.
Discover more from Web Strategy and Development News
Subscribe to get the latest posts sent to your email.