DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Creating a Secure REST API in Node.js
  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • Transforming Your Node.js REST API into an AI-Ready MCP Server
  • Designing Embedded Web Device Dashboards

Trending

  • Closing the Drift Loop: An AI Agent That Drafts Terraform Fixes
  • Applying Microservices Lessons to Multi-Agent AI Systems
  • Genkit Flows as senro Steps: Extremely Powerful AI Pipelines in Go
  • Why Kotlin or Java Is the Wrong Question For Enterprises

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. JavaScript
  4. Static Content, REST Endpoints, and WebSockets With Express and Node.js

Static Content, REST Endpoints, and WebSockets With Express and Node.js

Express is a simple framework for developing REST endpoints. See how to serve static content, REST endpoints, and WebSockets with Express and Node.js.

By 
Kevin Hooke
·
Apr. 05, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
18.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

I’ve yet to see a framework that is as simple as Express for developing REST endpoints. I’m experimenting with a React app that receives push updates from the server using Websockets. Is it possible to use Express to serve all the requests for this app: static content (the React app), REST endpoints. and Websocket? Turns out, yes — and it’s pretty easy, too.

Starting first using Express to serve static content:

var express = require('express');

//init Express
var app = express();

//init Express Router
var router = express.Router();
var port = process.env.PORT || 8080;

//connect path to router
app.use("/", router);
app.use(express.static('static'))
var server = app.listen(port, function () {
    console.log('node.js static server listening on port: ' + port)
})

This uses the static middleware for serving the static content.

Handling REST requests with Express is simple using the get(), post(), put(), and delete() functions on the Router. Adding an example for a GET for /status, now we have this:


var express = require('express');

//init Express
var app = express();

//init Express Router
var router = express.Router();
var port = process.env.PORT || 8080;

// GET /status
router.get('/status', function(req, res) {
    res.json({ status: 'App is running!' });
});

//connect path to router
app.use("/", router);
app.use(express.static('static'))

var server = app.listen(port, function () {
    console.log('node.js static content and REST server listening on port: ' + port)
})

Next, add support for Websockets using the ws library. Incrementally adding to the code above, now we create a WebSocket.Server, using the option to pass in the already created HTTP server: const wss = new SocketServer({ server });.

At this point, we add callbacks for connection and message events, and we’re in business:

const SocketServer = require('ws').Server;
var express = require('express');
var path = require('path');
var connectedUsers = [];

//init Express
var app = express();

//init Express Router
var router = express.Router();
var port = process.env.PORT || 80;

//return static page with websocket client
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/static/index-with-websockets.html'));
});

var server = app.listen(port, function () {
    console.log('node.js static server listening on port: ' + port + ", with websockets listener")
})

const wss = new SocketServer({ server });

//init Websocket ws and handle incoming connect requests
wss.on('connection', function connection(ws) {
    console.log("connection ...");

    //on connect message
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        connectedUsers.push(message);
    });

    ws.send('message from server at: ' + new Date());
});

This is the starting point for a React app to build a WebSockets client — more on that in a future post. The code so far is available in this GitHub repo.

REST Web Protocols Express WebSocket Node.js

Published at DZone with permission of Kevin Hooke. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Creating a Secure REST API in Node.js
  • GraphQL vs REST API: Which Is Better for Your Project in 2025?
  • Transforming Your Node.js REST API into an AI-Ready MCP Server
  • Designing Embedded Web Device Dashboards

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook