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
Over 2 million developers have joined DZone.
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

  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  • Why Round-Robin Won't Save You: Load Balancing Challenges in Data Streaming Services With Heterogeneous Traffic
  • Stateless JWT Auth Microservice Architecture With Spring Boot 3 and Redis Sentinel
  • Contract-First Integration: Building Scalable Systems With Flyway, OpenAPI, and Kafka
  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 user avatar
Kevin Hooke
·
Apr. 05, 17 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
17.9K Views

Join the DZone community and get the full member experience.

Join For Free

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

The likes didn't load as expected. Please refresh the page and try again.

  • 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