Getting Started

Prerequisites

Before we can get started, we'll need a few things:

1. Gleam: Statically typed functional language that compiles to Erlang. Install using the official installation guide.

2. NodeJS: JavaScript runtime built on Chrome's V8 JavaScript engine. Install using the official installation guide.

3. Yarn: Fast, reliable, and secure dependency management. Install using the official installation guide.

Setup

Method 1: Clone the starter project (Recommended)

This method is the easiest way to get started.

1. Clone the starter repository from GitHub

# Clone the starter repository from GitHub
git clone https://github.com/bitbldr/sprocket_starter.git

# Change into the project directory
cd sprocket_starter

2. Install dependencies

# Install dependencies
yarn

3. Start the server

# Start the server
yarn watch

Method 2: Add to existing project

This method is a bit more involved and assumes you already have a Gleam project. This section is intended to be a high-level overview of the steps involved rather than a comprehensive guide. When in doubt, refer to the starter repository on GitHub

1. Add Sprocket as a dependency

# Add Sprocket as a dependency in your gleam.toml
gleam add sprocket

2. Add client-side dependencies with the following commands

# Initialize a new NodeJS project, if you don't already have one
npm init -y

# Add sprocket-js as a client dependency
npm install sprocket-js

3. Sprocket needs to be initialized by the client in order to establish a persistent connection to the server. Add the following contents to your client entrypoint file (e.g. app.js)

import { connect } from "sprocket-js";

const hooks = {};

window.addEventListener("DOMContentLoaded", () => {
  const csrfToken = document
    .querySelector("meta[name=csrf-token]")
    ?.getAttribute("content");

  if (csrfToken) {
    let connectPath =
      window.location.pathname === "/"
        ? "/connect"
        : window.location.pathname.split("/").concat("connect").join("/");

    connect(connectPath, {
      csrfToken,
      hooks,
      // // Optionally, specify an element to mount to
      // targetEl: document.querySelector("#app") as Element,
    });
  } else {
    console.error("Missing CSRF token");
  }
});

4. Tailwind configuration is a bit involved and is out of scope for this guide. If you wish to follow along with the same styles in this documentation, you can install tailwind by following the instructions in the Tailwind CSS installation guide and taking a look at the configuration in the starter repository on GitHub.

That's it! Now we can begin our journey to learning how to build real-time server-side components with Sprocket!