Site.js

Small Web construction set.

The Small Web is for people (not startups, enterprises, or governments).

Develop, test, sync, and deploy (using a single tool that comes in a single binary).

Get started in seconds

  1. Install Site.js.

    Launch a terminal window (on Windows, a PowerShell session running under Windows Terminal) and follow along.

    Linux

    wget -qO- https://sitejs.org/install | bash

    macOS

    curl -s https://sitejs.org/install | bash

    Windows

    iex(iwr -UseBasicParsing https://sitejs.org/install.txt).Content
  2. Create a basic static web page.

    1. Create a folder.

      mkdir hello-world
    2. Enter the folder.

      cd hello-world
    3. Write the string 'Hello, world' into a file called index.html, creating or overwriting it as necessary.

      Linux and macOS

      echo 'Hello, world' > index.html

      Windows

      echo 'Hello, world' | Out-File -Encoding UTF8 index.html
  3. Start the server.

    site

    Site.js starts serving your hello-world site at https://localhost. Go there in your browser to see your “Hello, world!” message.

    Congratulations, you’re up and running with Site.js!

Static sites with Hugo

The type of site you just created is an old-school static site. You can create static sites with Site.js using plain old HTML, CSS, and JavaScript. Site.js will automatically serve any files it finds in the folder you start it on as static files.

For larger sites, hand-rolling your static site might become cumbersome. That’s why Site.js comes bundled with the Hugo static site generator.

Let’s create a new Hugo site and start serving it.

  1. Set up a new project.

    1. Create a folder.

      mkdir my-hugo-site
    2. Enter the folder.

      cd my-hugo-site
  2. Create a new Hugo site.

    site hugo new site .hugo
  3. Create a basic page layout.

    Linux and macOS

    echo '<body><h1>Hello, world!</h1></body>' > .hugo/layouts/index.html

    Windows

    echo '<body><h1>Hello, world!</h1></body>' | Out-File -Encoding UTF8 .hugo/layouts/index.html
  4. Start the server.

    site

    Site.js starts serving your Hugo site at https://localhost. Go there in your browser to see your “Hello, world!” message.

    Congratulations, you just created your first Hugo site with Site.js!

Dynamic sites with DotJS

Site.js does not limit you to creating and serving fully static sites. You can easily add dynamic functionality to your static sites or create fully dynamic sites.

The easiest way to get started with dynamic sites is to use DotJS. DotJS gives you PHP-like simplicity in JavaScript using simple .js files.

Follow along to create a very basic dynamic site that updates a counter every time the home page is reloaded.

  1. Create the project structure.

    1. Create the folders.

      Make a project folder called count and a special nested folder in that called .dynamic:

      mkdir -p count/.dynamic
    2. Enter the dynamic routes folder.

      cd count/.dynamic
  2. Create a dynamic route.

    Make a file called index.js that holds the dynamic counter route:

    Linux and macOS

    echo 'i=0; module.exports=(_, res) => res.html(`${++i}`)' > index.js

    Windows

    echo 'i=0; module.exports=(_, res) => res.html(`${++i}`)' | Out-File -Encoding UTF8 index.js
  3. Serve your site.

    site ..

    Hit https://localhost and refresh to see the counter update.

    Congratulations, you just made your first fully dynamic DotJS site!

WebSockets

In addition to static routes and dynamic HTTPS routes, you can also specify secure WebSocket (WSS) routes in DotJS. And you can mix all three types of routes as you please.

To see WebSockets in action, let’s create a very simple chat app.

  1. Create the project structure.

    mkdir -p chat/.dynamic/.wss
  2. Create the chat server.

    Linux and macOS

    echo '
      module.exports = function (client, request) {
        // Set the room based on the route’s URL.
        client.room = this.setRoom(request)
    
        // Create a message handler.
        client.on("message", message => {
          // Broadcast a received message to everyone in the room.
          this.broadcast(client, message)
        })
      }
    ' > chat/.dynamic/.wss/chat.js

    Windows

    echo '
      module.exports = function (client, request) {
        // Set the room based on the route URL.
        client.room = this.setRoom(request)
    
        // Create a message handler.
        client.on("message", message => {
          // Broadcast a received message to everyone in the room.
          this.broadcast(client, message)
        })
      }
    ' | Out-File -Encoding UTF8 chat/.dynamic/.wss/chat.js
  3. Create the chat client.

    Linux and macOS

    echo '
      <!doctype html>
      <html lang="en">
      <title>Chat</title>
      <h1>Chat</h1>
      <form name="messageForm">
        <input name="message" type="text">
        <button>Send</button>
      </form>
      <h2>Messages</h2>
      <ul id="messageList"></ul>
      <script>
        const socket = new WebSocket(`wss://${window.location.hostname}/chat`)
    
        const showMessage = message => {
          const list = document.querySelector("#messageList")
          list.innerHTML += `<li>${message.text}</li>`
        }
    
        socket.onmessage = message => {
          showMessage(JSON.parse(message.data))
        }
    
        document.messageForm.addEventListener("submit", event => {
          const message ={ text: event.target.message.value }
          socket.send(JSON.stringify(message))
          showMessage(message)
          event.preventDefault()
        })
      </script>
    ' > chat/index.html

    Windows

    echo '
    <!doctype html>
    <html lang="en">
    <title>Chat</title>
    <h1>Chat</h1>
    <form name="messageForm">
      <input name="message" type="text">
      <button>Send</button>
    </form>
    <h2>Messages</h2>
    <ul id="messageList"></ul>
    <script>
      const socket = new WebSocket(`wss://${window.location.hostname}/chat`)
    
      const showMessage = message => {
        const list = document.querySelector("#messageList")
        list.innerHTML += `<li>${message.text}</li>`
      }
    
      socket.onmessage = message => {
        showMessage(JSON.parse(message.data))
      }
    
      document.messageForm.addEventListener("submit", event => {
        const message ={ text: event.target.message.value }
        socket.send(JSON.stringify(message))
        showMessage(message)
        event.preventDefault()
      })
    </script>
    '| Out-File -Encoding UTF8 chat/index.html
  4. Launch the server.

    site chat

    Start the server.

    To test your chat app, open up two or more web browser windows at https://localhost and play with the chat interface.

Database

Site.js also has a fast and simple JavaScript Database (JSDB) built into it. You can refer to the database for your app any of your routes using the global db instance.

Let’s see how easy it is to use JSDB by persisting the messages our simple chat app.

  1. Update the server.

    The code you need to add is presented in boldface.

    module.exports = function (client, request) {
      // Ensure the messages table exists.
      if (!db.messages) {
        db.messages = []
      }
    
      // Set the room based on the route’s URL.
      client.room = this.setRoom(request)
    
      // Send new clients all existing messages.
      client.send(JSON.stringify(db.messages))
    
      // Create a message handler.
      client.on('message', message => {
        // Parse the message JSON string into a JavaScript object.
        const parsedMessage = JSON.parse(message)
    
        // Persist the message.
        db.messages.push(parsedMessage)
    
        // Broadcast a received message to everyone in the room.
        this.broadcast(client, message)
      })
    }
  2. Update the client.

    You need to update the client so that it can handle the initial list of messages that is sent when someone joins the chat.

    Again, the code you need to add is presented in boldface.

    <!doctype html>
    <html lang="en">
    <title>Chat</title>
    <h1>Chat</h1>
    <form name="messageForm">
      <input name="message" type="text">
      <button>Send</button>
    </form>
    <h2>Messages</h2>
    <ul id="messageList"></ul>
    <script>
      const socket = new WebSocket(`wss://${window.location.hostname}/chat`)
    
      const showMessage = message => {
        const list = document.querySelector("#messageList")
        list.innerHTML += `<li>${message.text}</li>`
      }
    
      socket.onmessage = websocketMessage => {
        // Deserialise the data.
        const data = JSON.parse(websocketMessage.data)
    
        if (Array.isArray(data)) {
          // Display initial list of messages we get when we join a room.
          data.forEach(message => showMessage(message))
        } else {
          // Display a single message.
          showMessage(data)
        }
      }
    
      document.messageForm.addEventListener("submit", event => {
        const message = { text: event.target.message.value }
        socket.send(JSON.stringify(message))
        showMessage(message)
        event.preventDefault()
      })
    </script>

Proxy servers

You can use Site.js as a proxy to add automatic TLS for HTTP and WebSocket to any web app.

  1. Create a simple insecure service

    ForThe following is a simple HTTP server written in Python 3 (server.py) that runs insecurely on port 3000:

    from http.server import HTTPServer, BaseHTTPRequestHandler
    class MyRequestHandler(BaseHTTPRequestHandler):
      def do_GET(self):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b'Hello, from Python!')
    
    server = HTTPServer(('localhost', 3000), MyRequestHandler)
    server.serve_forever()
                
  2. Run it

    To keep things simple, the following command will simply run it in the background.

    $ python3 server &
  3. Serve it securely using Site.js

    $ site enable :3000

Further reading

Like this? Fund us!

Made with love by Small Technology Foundation.

We are a tiny not-for-profit based in Ireland that makes tools for people like you – not for startups, enterprises, or governments. And we’re also funded by people like you. If you like our work and want to help us continue to exist, please fund us.

Site.js is Small Technology.