Skip to content

ministryofjustice/govuk-frontend-express

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

77 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

GOVUK Frontend Express

Standards Icon

govuk-frontend 5.8.0

Express.js is a fast, unopinionated, minimalist web framework for Node.js.

GOVUK Frontend Express is a community tool using the GOV.UK Design System. The Design System team is not responsible for it and cannot support you with using it. Contact the maintainers directly if you need help or you want to request a feature.

This is a template app using the GOV.UK Frontend and GOV.UK Design System which is designed to get a new project started quicker.

The app is provided intentionally bare, with just the essential parts that all services need, such as error pages, accessibility statement and privacy notice. It uses a number of other packages to provide the features described below with sensible and best-practice defaults. Please read the next steps section for guidance on how to start building out your app on top of this template.

Contents

Prerequisites

  • node stable version [22.13.1]

Getting started

Set local environment variables

Create your local config file .env from the template file:

cp .env.example .env

Align to the Node Version specified for this project

If using Node Version Manager (nvm), use the following command to switch to the correct version:

nvm use
nvm install

Install dependencies and run application for development

npm install
npm run build
npm run dev

Then, load http://localhost:3000/ in your browser to access the app.

Install dependencies and run application for production

npm install
npm run build
npm run start

Node Version Manager

You may have to tell your local machine to use the latest version of node already installed on your device, before installing and running the application. Use the following command.

nvm install node

Routing

This template uses the built-in Express JS routing.

A route is a section of Express code that associates an HTTP verb (GET, POST, PUT, DELETE, etc.), a URL path/pattern, and a function that is called to handle that pattern.

You can find further documentation here.

Testing

There are many frameworks to test your Express.js application (a few of these frameworks will be signposted below), but you will want to split out your test suite to cover:

  • Unit Tests - test individual code components to ensure each function operates as intended.
  • Integration Tests - assess the coherence of the entire application, ensuring smooth interactions between various parts.
  • End-to-end (E2E) Tests - assess the entire software system, from the user interface to the database.

Unit/Integration Testing example frameworks

  • Choose a testing framework (e.g., Mocha, Jest).
  • Write test cases for individual functions and combined modules.
  • Mock dependencies (e.g., databases, external services).
  • Run tests and check outputs against expected results.

E2E Testing example frameworks

  • Choose an E2E testing tool (e.g., Cypress, Selenium).
  • Write test scripts simulating user interactions.
  • Set up a test environment mirroring production.
  • Run tests and verify overall application behaviour.

Features

Asset management

This is node.js scripts at them moment, but ESBuild coming soon.

Cache busting

Caching allows Express.js applications to store and serve frequently requested data efficiently, reducing the strain on servers and minimizing latency. This template improves caching through:

  • intelligent browser caching, when using the template for development of an application
  • employing a package management tool, to improve the caching process of installing, upgrading, configuring, and removing software from your application

Form validation

This template app contains a basic demo for form validation, when running this app locally. You can find further information on the validation used, by searching in the Express documentation

CSRF protection

The template uses the csrf-sync middleware, to help keep your app secure.

Content Security Policy (CSP)

This app uses helmet.js to help secure this Express.js template app by setting HTTP response headers, which includes your CSP.

Response compression

The app uses a Node.js compression middleware called compression. The middleware will attempt to compress response bodies for all request that traverse through the middleware, based on the given options.

Rate limiting

This template uses a basic rate-limiting middleware for Express.js, called express-rate-limit. It is used to limit repeated requests to public APIs and/or endpoints such as password reset.

For further information please visit the documentation here.

Nunjucks support

A rich, high-performance JavaScript templating language, supported by all modern browsers. Nunjucks is customisable with extensions and filters; it offers inheritance, asynchronous control, auto escaping and other features.

Nunjucks documentation.

ES6 JS Documentation

ES6 refers to version 6 of the ECMA Script programming language. ECMA Script is the standardized name for JavaScript, and version 6 is the next version after version 5, released in 2011. It is a significant enhancement to the JavaScript language and adds many more features to simplify large-scale software development.

Find out more here.

Linter

ESLint is a static code analysis tool for identifying and fixing problems in JavaScript code. It helps maintain code quality and consistency across a project by enforcing a set of coding standards and best practices. ESLint can catch syntax errors, stylistic issues, and potential bugs before they become actual problems.

To run ESlint:

npm run lint

Axios

Within this template axios with middleware-axios (used as a utility ../utils/axiosSetup.mjs, and can be extended with further middleware) is set up and ready to use out of the box.

Below is an example of implementation of how to use the axios_api function, in other modules to make server/api calls:

// routes/index.mjs
import express from 'express';
const router = express.Router();
/* GET home page. */
router.get('/', (req, res, next) => {
  res.render('main/index', { title: 'Express' });
});
// Make an API call with `Axios` and `middleware-axios`
// GET users from external API
router.get('/users', async (req, res, next) => {
  try {
      // Use the wrapped Axios instance attached to the request object (via middleware-axios)
      const response = await req.axiosMiddleware.get('https://jsonplaceholder.typicode.com/users');
      res.json(response.data);
  } catch (error) {
      next(error);
  }
});
export default router;

SQLite database

In this template, SQLite3 is set up and ready to use out of the box. However, if you wish to use something else as your database, please see Database integration Options.

You'll find 2 main js files: utils/sqliteSetup.js & middleware/setupDB.js.

  • utils/sqliteSetup.js, is where you can make your database connection and initialise your database schema. In this template we create a dummy users table with id, name, and email fields.
  // Initialize your database schema here.
  await db.exec(`
    CREATE TABLE IF NOT EXISTS users (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      email TEXT NOT NULL UNIQUE
    )
  `);
  • middleware/setupDB.js, is set up to allow database queries to be run against your SQLite3. It sets up your database to access any of your routes, such as this example below.
router.get('/users', async (req, res, next) => {
  try {
    const rows = await req.db.all("SELECT * FROM users");
    res.json({ users: rows });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

Further reading

Please refer to the specific packages documentation for more details.

Contributors

Support

This software is provided "as-is" without warranty. Support is provided on a "best endeavours" basis by the maintainers and open source community.

If you are a civil servant you can sign up to the UK Government Digital Slack workspace to contact the maintainers listed above and the community of people using this project in the #govuk-design-system channel.

Manage Outside Collaborators

To add an Outside Collaborator to the repository, follow the guidelines detailed here.

Acknowledgment and Attribution

If you find this project helpful and decide to use it in your own work, we kindly ask that you give proper credit to this repository. A simple acknowledgment in your project's documentation, website, or application would be greatly appreciated. Here are a few ways you can do this:

  • Link back to this repository: Include a link to this GitHub repository in your project's documentation or README file.
  • Mention our contribution: When discussing your project or presenting it to others, please mention that part of your project is based on our work.
  • Cite our work: If your project includes a list of contributors or a "Credits" section, consider adding our repository as one of the sources.
This project uses code from [Your Repository Name](https://github.com/yourusername/your-repository), originally developed by [Your Name or Organization].

Thank you for your support and for helping to spread the word about our work!

Licence

Licence

About

GOVUK Frontend Express JS Skeleton to be used to help frontend projects.

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 6