Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active March 12, 2021 00:21
Show Gist options
  • Save acidtone/e2590b67f8fd701a36f7a04e62caa594 to your computer and use it in GitHub Desktop.
Save acidtone/e2590b67f8fd701a36f7a04e62caa594 to your computer and use it in GitHub Desktop.
Express: Create static web server

Express: Serving static files

Prerequisites

  1. Express "Hello World!" app created.

Example directory structure

project-root
    └─ node_modules
    └─ public
       └─ css
          └─ main.css
       └─ images
          └─ example.webp
       └─ js
          └─ client.js
       └─ index.html
    ├─ package-lock.json
    ├─ package.json
    └─ server.js

Instructions

  1. Create a Hello World! express app or use an existing express project.

  2. Add express.static middleware before any other middleware that sends a response (i.e. app.get()). This checks if a request URL matches a static file located anywhere in the public directory.

    app.use(express.static(path.join(__dirname, 'public')));
    • Don't forget to put your website files in ./public. If one of your files is found, it's returned as a response back to the client. Magic!
    • Placing this middleware above other server responses (and database connections) saves server resources by sending a response before middleware functions are needlessly called.

Related Gists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment