Build Simple Authentication in Express

  • 2018-11-30 02:17 AM
  • 123

Building web pages with user authentication can be a huge pain. You typically need to set up some sort of database to manage users even if you're not using the database for anything else. You would then need to store their password hashes, and you almost need a degree on internet security to know the safest ways to do that.

Aiodex’s Referral Program will give you 20% -80% commission from their transaction fee for 7 years. The value will be calculated starting from the date the member you invite sign up. Starting from the first year is 20%, after each year increased to 10% from the first day of next year. For the 300K members who are enjoying the transaction fee refund policy, if they are one of your invited members, you will receive a commission until the system start charging their transaction fees. For example, if the new system start charging from 2020–01–01, you will start receiving commissions and since it is the second year then you will receive 30% ☞
Get Free 15 Geek ☞ or
Learn to Code ☞
CodeGeek’s Discuss ☞
Playlists Video Tutorial ☞

What if I told you it didn’t have to be so complicated? Using Okta and Express, I’ll show you how to really quickly set up a website that has secure user authentication, without the need for a separate database. Everything you need you could deploy anywhere that you can run Node.

Create a New App in Express

Creating a new app in Express doesn’t take a lot of code. You’ll need to set up your project structure and install some dependencies, which you can do with just a few commands:

mkdir new-project
cd new-project
npm init -y
npm install [email protected] [email protected]
npm install --save-dev [email protected] [email protected]

Edit the "scripts" section of your package.json to look like this:

"scripts": {
  "start": "nodemon .",
  "test": "standard"

Now create a new file index.js :


const express = require('express')
const path = require('path')

const app = express()

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'hbs')

app.use(express.urlencoded({ extended: true }))
app.use('/static', express.static('public'))

// @TODO add auth middleware
// @TODO add registration page
// @TODO add logout route

app.use('/', require('./routes/index'))

const port = process.env.PORT || 3000
app.listen(port, () => console.log(`App listening on port ${port}`))

Make a few new folders as well:

mkdir -p public/images routes views

Put a fun greeting image in public/images/greeting.jpg that you will use to greet users.

Express allows for a templating engine. You already set up Handlebars (hbs) above, so now you can create a couple of views. One will be the HTML skeleton that contains the basic markup, and the other will be your homepage (the index view).


<!doctype html>
<html lang="en">

  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"

  <title>Simple Auth in 15 Minutes</title>

  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container">
      <a class="navbar-brand" href="/">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
        aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
          {{!-- @TODO add auth links --}}
  <main class="container pt-4">{{{body}}}</main>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
  <script src="" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
  <script src="" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"


This layout will get rendered for each view, with the specific view replacing the {{{body}}} tag.

Now you can create the indexview. This will just display the image you put in public/images/greeting.jpg :


<div class="d-flex justify-content-center">
  <img class="rounded img-fluid" src="/static/images/greeting.jpg" />

To tell the homepage to use that file when rendering, you’ll also need to create a router. You already required routes/index.jsin the index.js file of your app, so now you just need to create that file:


const express = require('express')
const router = express.Router()

router.get('/', (req, res) => {

module.exports = router

The call to res.render('index') tells Express to use the render the index.hbs view and respond with the results back to the client. You can also pass in some context, but it’s not needed here just yet.

Now you can run your server with the following command (as you make changes, the server will reload and you’ll just need to refresh the page):

npm start

Go to http://localhost:3000 to see your greeting.

Add Authentication to Your Express App

You now have a simple web server with a homepage and a lovely greeting image. The next step I promised to show you is to add secure user authentication. This is where Okta comes in to play. Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:

  • Authenticate and authorize your users

  • Store data about your users

  • Perform password-based and social login

  • Secure your application with multi-factor authentication

  • And much more! Check out our product documentation

If you don’t already have one, sign up for a forever-free developer account.

You’re going to need to save some information to use in the app. Create a new file named .env in the root of your application. In it, enter your organization URL.


You will also need a random string to use as an App Secret for sessions. You can generate this with the following command:

npm install -g uuid-cli
echo "APP_SECRET=`uuid`" >> .env

Next, log in to your Okta developer console, navigate to Applications, then click Add Application. Select Web, then click Next.

The page you come to after creating an application has some more information you need to save to your .env file. Copy in the client ID and client secret.


At the time of this writing, the default application creation page does not allow you to add a Logout redirect URI, but you can add one after creating the application. After creating the application, click Edit, then next to Logout redirect URIs click Add URI. Add a logout redirect URI of http://localhost:3000 and click Save.

The last piece of information you need from Okta is an API token. In your developer console, navigate to API -> Tokens, then click on Create Token. You can have many tokens, so just give this one a name that reminds you what it’s for, like “15 Minute Auth”. You’ll be given a token that you can only see right now. If you lose the token, you’ll have to create another one. Add this to .env also.


Add Auth Middleware to Your Express App

Okta provides some middleware that will give you information about whether the user is registered or not. It also gives you a login page by default at /login . Add the following dependencies:

npm install [email protected] [email protected] @okta/[email protected] @okta/o[email protected]

In your index.js page, replace the // @TODO add auth middleware comment with the following code:

  secret: process.env.APP_SECRET,
  resave: true,
  saveUninitialized: false

const { ExpressOIDC } = require('@okta/oidc-middleware')
const oidc = new ExpressOIDC({
  issuer: `${process.env.OKTA_ORG_URL}/oauth2/default`,
  client_id: process.env.OKTA_CLIENT_ID,
  client_secret: process.env.OKTA_CLIENT_SECRET,
  redirect_uri: `${process.env.HOST_URL}/authorization-code/callback`,
  scope: 'openid profile'


Also, make sure to add the following to the very top of index.js . This needs to be there before any other code in order to load your environment variables, so it should be the very first line of the file:


Create a Registration Page

You should now be able to login by going to /login . This will redirect you to your Okta developer page, and after you sign in you’ll be redirected back to the homepage.

For people who aren’t registered yet, they’ll need a registration page. At the time of this writing, Okta doesn’t provide a registration page out of the box, but you can build one pretty quickly. Create a new view for your route:


<form method="post">
  {{#each fields}}
  <div class="form-group">
      class="form-control {{#if this.error}}is-invalid{{/if}}"
    <div class="invalid-feedback">{{this.error}}</div>
  <button type="submit" class="btn btn-primary">Register</button>

You’ll also need a new route:


const okta = require('@okta/okta-sdk-nodejs')
const express = require('express')

const router = express.Router()

const client = new okta.Client({
  orgUrl: process.env.OKTA_ORG_URL,
  token: process.env.OKTA_TOKEN

// Take the user to the homepage if they're already logged in
router.use('/', (req, res, next) => {
  if (req.userContext) {
    return res.redirect('/')

const fields = [
  { name: 'firstName', label: 'First Name' },
  { name: 'lastName', label: 'Last Name' },
  { name: 'email', label: 'Email', type: 'email' },
  { name: 'password', label: 'Password', type: 'password' }

router.get('/', (req, res) => {
  res.render('register', { fields })
})'/', async (req, res) => {
  const { body } = req

  try {
    await client.createUser({
      profile: {
        firstName: body.firstName,
        lastName: body.lastName,
      credentials: {
        password: {
          value: body.password

  } catch ({ errorCauses }) {
    const errors = {}

    errorCauses.forEach(({ errorSummary }) => {
      const [, field, error] = /^(.+?): (.+)$/.exec(errorSummary)
      errors[field] = error

    res.render('register', {
      fields: => ({
        error: errors[],
        value: body[]

module.exports = router

To tie this all together, in your root index.js file, make sure to replace the // @TODO add registration page comment with the following:

app.use('/register', require('./routes/register'))

You can now have users register. If they run into an error, it will be displayed with the field that caused the error.

Add a Logout Route

At the time of this writing, Okta’s middleware doesn’t provide a default /logout route. Luckily, adding one is fairly simple. In your index.js file, replace the // @TODO add logout route comment with:

app.get('/logout', (req, res) => {
  if (req.userContext) {
    const idToken = req.userContext.tokens.id_token
    const to = encodeURI(process.env.HOST_URL)
    const params = id_token_hint=${idToken}&post_logout_redirect_uri=${to}
  } else {

If you’re logged in, this will invalidate the token and delete the user’s session. It will then redirect you back to the homepage. If you’re not logged in, it just takes you back to the homepage.

Add Links to the New Routes in Your Express App

To more easily expose these routes to the user, you can add some buttons. You’ll need to expose the user context to the view to know if a user is logged in or not so you know which buttons to display, and potentially greet the user.

In routes/index.js replace the res.render('index') line with the following:


const { userContext } = req
res.render('index', { userContext })

While you’re at it, you can also prevent the user from seeing your greeting unless they’re logged in. Change your views/index.hbs file to the following:


{{#if userContext}}
  <h1 class="text-center">Hi {{userContext.userinfo.given_name}}!</h1>
  <div class="d-flex justify-content-center">
    <img class="rounded img-fluid" src="/static/images/greeting.jpg" />
  <h1 class="text-center">Please log in</h1>

Now to add the buttons. In views/layout.hbs, replace the {{!-- @TODO add auth links --}} comment with the following:


{{#if userContext}}
  <a class="nav-item nav-link" href="/logout">Log out</a>
  <a class="nav-item nav-link" href="/login">Log in</a>
  <a class="nav-item nav-link" href="/register">Register</a>

Check out the final product to make sure it works

Learn More

Modern React with Redux

Become a JavaScript developer - Learn (React, Node,Angular)

The Complete React Web Developer Course (2nd Edition)

Node with React: Fullstack Web Development

Beginner Full Stack Web Development: HTML, CSS, React & Node

React JS and Redux - Mastering Web Apps