Back to the notebook

Using SVR.js to Run Server-Side JavaScript

Nasa Space Photo
Photo by NASA on Unsplash

TL;DR: Updated project code here: github.com/andyj/svrjs-with-docker

How to Use SVR.js to Run Server-Side JavaScript

Building on the Basics

In my previous post, How to Run SVR.js with Docker Compose, I introduced a simple way to set up SVR.js for serving static files using Docker Compose. Since then, I’ve expanded the project to explore server-side capabilities of SVR.js.

To accommodate this, the project structure has evolved on GitHub, and now includes multiple folders for different setups. Specifically, the new 2.serverside-javascript-svrjs folder demonstrates how to run server-side JavaScript. Let’s dive in!

Updated Project Structure

svrjs-with-docker/
├── 1. how-to-run-svrjs-with-docker-compose
│   ├── README.md
│   ├── docker-compose.yml
│   ├── svrjs-config.json
│   └── www
│       ├── index.html
│       └── style.css
├── 2.serverside-javascript-svrjs
│   ├── README.md
│   ├── docker-compose.yml
│   ├── server
│   │   └── time.js
│   ├── svrjs-config.json
│   └── www
│       ├── index.html
│       └── style.css
├── LICENSE
└── README.md

Step 1: The Configuration File

The new svrjs-config.json enables server-side JavaScript by defining a route that maps to a server-side script:

{
"port": 80,
"wwwroot": "/var/www/svrjs",
"logging": {
  "enabled": true,
  "level": "info"
},
"routes": {
  "/time": "../server/time.js"
}
}

Step 2: Writing Server-Side Logic

Create the time.js file in the server folder:

module.exports = (req, res) => {
  const currentTime = new Date().toLocaleString();
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify({ message: "Hello, World!", time: currentTime }));
};

Step 3: Updated Docker Compose Configuration

Here’s the docker-compose.yml file for this setup:

services:
svrjs:
  image: svrjs/svrjs:lts
  container_name: svrjs-server
  platform: linux/amd64
  ports:
    - "8282:80"
  volumes:
    - ./www:/var/www/svrjs
    - ./server:/var/server
    - ./svrjs-config.json:/etc/svrjs-config.json
  restart: always

Step 4: Running the Server

Run the following command from the 2.serverside-javascript-svrjs directory:

docker compose up

Once the container is running, navigate to:

Testing the Endpoint

Visiting /time in your browser or via a tool like curl will return a JSON response similar to:

{
"message": "Hello, World!",
"time": "28/11/2024, 15:00:00"
}

Conclusion

With minimal effort, SVR.js transforms from a static file server into a lightweight tool for handling server-side JavaScript. By leveraging Docker for deployment, this setup is both portable and scalable.

What server-side features will you build next with SVR.js? Let me know in the comments or contribute to the project on GitHub!

Leave a note.