bootstrap, express, node, sass

Bootstrap and Express app

Integrating Bootstrap with an Express app

Introduction

In this tutorial we will be integrating Bootstrap into an Express app and dynamically generating custom themes using Sass.

Express is a minimal and flexible Node web application framework that provides a robust set of features for web and mobile applications. Express is our first choice as an non-opinionated framework and it has a very light footprint, very broad following and huge number of useful packages.

Bootstrap is the most popular CSS framework featuring responsive design, extensive prebuilt components and powerful JavaScript plugins.

The easiest way to use Bootstrap is to simply link css styles and JavaScript libraries directly from your HTML files. However, if you want to build beautiful custom Bootstrap themes and templates, you need a more powerful solution.

In this tutorial we will integrate powerful Bootstrap Sass features to create custom themes right within your Express app.

All files for this tutorial are available at regbrain/express-bootstrap git repo.

Basic project set up

Go to your terminal and create a new directory for our app:

mkdir express-bootstrap

Go to the new directory and initiate a new package:

Note: we strongly suggest using Yarn as a package manager. We prefer to use Yarn as a package manager as it provides more stable installations for large repositories. See this article on why it is worth using yarn over npm.

cd express-bootstrap
yarn init

respond to all the prompts. For this tutorial it doesn't matter what you put as your responses as these just describe your package for other users.

Install required dependencies

We will continue work in terminal in your project directory to install all the required dependencies.

First, install Express:

// yarn
yarn add express

Install node-sass-middleware. We will use this package to compile custom Bootstrap css files on the fly.

yarn add node-sass-middleware

Install Bootstrap. As we want to be able to customize Bootstrap to create our own templates and styles, we will use Bootstrap sass files and compile them on the fly later in our application.

yarn add bootstrap

Finally, we need to choose a template engine to display HTML pages in our Express app. We have a strong preference for Nunjucks over other JS templating engines:

yarn add nunjucks

Okay, so you have all the required dependencies installed. Let's move on to building our app.

Set up basic Express app

In your code editor, go to your app directory and create a file app.js.

We will be working in app.js now to create a fully working Express application with Bootstrap integration.

Let's start by requiring all the dependencies:

let express = require('express')
let http = require('http')
let nunjucks = require('nunjucks')
let path = require('path')
let sassMiddleware = require('node-sass-middleware')

If you are wondering why have not installed http and path and are requiring them above - don't worry, they are available in Node by default.

Create an Express app:

let app = express()

Configure Nunjucks templates - we have another full tutorial on using Nunjucks with Express app if you are interested in this powerful templating engine:

nunjucks.configure('views', {
  autoescape: true,
  express: app
})

Now comes the key piece of the code. We are setting up sassMiddleware to compile Sass files from src directory into dest directory. In our case, we will keep Sass files in a bootstrap directory and compile final css into public directory:

app.use(sassMiddleware({
  src: path.join(__dirname, 'bootstrap'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true, // true = .sass and false = .scss
  sourceMap: true
}))

Since our css file will be saved into public directory, the last task is to configure our Express app to serve static files from public directory:

app.use(express.static(path.join(__dirname, 'public')))

Okay, so all the hard work and integration is done. Now let's just define a simple route to test our application. The key element here is data object which we are using to pass content to the template.

app.get('/', function(req, res, next) {
  let  data = {
    content: 'Hello world!',
    title: 'Bootstrap example'
  }

  // this renders 'data' into Nunjucks template 'index.njk'
  res.render('index.njk', data)
})

We still need to create a simple index.njk template and integrate Bootstrap styles and js file there but before we do that, let's just finish our Express application by creating a http server and initiating the server to listen on port 3000:

let server = http.createServer(app)
server.listen('3000')

That's it. Our basic Express app file with Bootstrap integration is complete. We have two tasks left to do: creating a template index.njk and a sass file with custom Bootstrap styles.

Before we move on, the full app.js file should look like this:

let express = require('express')
let http = require('http')
let nunjucks = require('nunjucks')
let path = require('path')
let sassMiddleware = require('node-sass-middleware')

let app = express()

nunjucks.configure('views', {
  autoescape: true,
  express: app
})

app.use(sassMiddleware({
  src: path.join(__dirname, 'bootstrap'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true, // true = .sass and false = .scss
  sourceMap: true
}))

app.use(express.static(path.join(__dirname, 'public')))

app.get('/', function(req, res, next) {
  let  data = {
    content: 'Hello world!',
    title: 'Bootstrap example'
  }

  res.render('index.njk', data)
})

let server = http.createServer(app)

server.listen('3000', () => {
  console.log('Listening on port 3000')
})

Create a template with Bootstrap integration

In the main app directory, create views directory. Go to views and create index.njk. We will now work in index.njk to integrate Bootstrap components and data from our Express app:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <!-- this is a link to the css file -->
    <link rel="stylesheet" href="/style.css" />

    <!-- remember to include custom fonts - if you are using them -->
    <link href="https://fonts.googleapis.com/css2?family=Zilla+Slab:wght@700&display=swap" rel="stylesheet">

    <!-- title is a Nunjucks variable -->
    <title>{{ title }}</title>
  </head>
  <body>
    <!-- do you recognize Bootstrap classes? -->
    <div class="container">
      <h1>Bootstrap demo</h1>

      <!-- content is a Nunjucks variable -->
      {{ content }}
    <div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
  </body>
</html>

Following is the explanation of the key components of the template above:

{{ content }}

this is Nunjucks variable declaration. In our example, value of data.content will be displayed here.

<link rel="stylesheet" href="/style.css" />

this is a link to the Bootstrap css file dynamically created by our sassMiddleware

<link href="https://fonts.googleapis.com/css2?family=Zilla+Slab:wght@700&display=swap" rel="stylesheet">

we are importing a custom font that we will use in our theme

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

we are including Bootstrap JavaScript core files and dependencies

Create custom Bootstrap sass files

This is the last part of our demo Bootstrap integration. We will create a Sass file where we will import all the standard Bootstrap variables and style and we will be able to customize our theme using that file.

In the main application directory create bootstrap directory. Go to bootstrap directory and create a style.sass file:

$body-bg: #C0C0C0

@import "../node_modules/bootstrap/scss/bootstrap"

h1, h2, h3, h4
  font-family: 'Zilla Slab', serif
  font-weight: 700

In the example above we overwrite default background colour $body-gb variable and we add some custom styling to headings. For more details on how to structure custom sass files see theming in Boostrap documentation.

Our sassMiddleware takes the Sass file and compiles it to a css output which is then linked from our template file.

Test your application

In your terminal window, go to the main application directory and run your app:

node app

In your browser, go to: http://localhost:3000/ and you should see a message "Bootstrap demo Hello world!" with a custom background colour and Zilla Slab font for headings.

Bootstrap demo app

Now you know how to build custom Bootstrap themes. You can harness the full power of Sass, Bootstrap and Express apps to build beautiful Node powered websites!

Next step: see how to integrate free Font Awesome icons with the Bootstrap-Express app

Powered by

Node
Github
Copyright 2019 - present