FastCGI

FastCGI mode keeps js-cgi running as a persistent process, eliminating the overhead of spawning a new process per request. This is the recommended mode for production deployments with Nginx.

Starting the FastCGI Server

# Listen on a TCP port
js-cgi --fastcgi 9000

# Listen on a Unix socket
js-cgi --fastcgi /var/run/js-cgi.sock

# Specify host and port
js-cgi --fastcgi 127.0.0.1:9000

# Set number of worker processes (default: 4)
js-cgi --fastcgi 9000 --workers 8

# With a custom ini file
js-cgi --ini=/etc/js-cgi/js-cgi.ini --fastcgi /var/run/js-cgi.sock --workers 4

How It Works

  • A master process forks N worker processes
  • Workers accept connections and handle FastCGI requests
  • Each request gets a fresh JavaScript context (no state leakage between requests)
  • Scripts are re-read from disk on every request (edits take effect immediately)
  • Crashed workers are automatically restarted by the master

Nginx Configuration

server {
    listen 80;
    server_name myapp.com;
    root /var/www/myapp;
    index index.js index.html;

    # Serve static files directly
    location ~* \.(css|js|png|jpg|gif|ico|svg|woff2?|ttf)$ {
        try_files $uri =404;
    }

    # Pass .js files to js-cgi FastCGI
    location ~ \.js$ {
        fastcgi_pass unix:/var/run/js-cgi.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Apache Configuration (mod_proxy_fcgi)

<VirtualHost *:80>
    ServerName myapp.com
    DocumentRoot /var/www/myapp

    <FilesMatch "\.js$">
        SetHandler "proxy:fcgi://127.0.0.1:9000"
    </FilesMatch>
</VirtualHost>

Systemd Service

Run js-cgi as a system service so it starts automatically on boot:

[Unit]
Description=js-cgi FastCGI server
After=network.target

[Service]
Type=simple
ExecStart=/usr/lib/cgi-bin/js-cgi --fastcgi /var/run/js-cgi.sock --workers 4
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
sudo systemctl enable js-cgi
sudo systemctl start js-cgi

Unix Socket vs TCP

Unix SocketTCP
PerformanceSlightly faster (no network overhead)Standard
Remote accessSame machine onlyAny machine on the network
Configuration/var/run/js-cgi.sock127.0.0.1:9000

Use Unix sockets when Nginx and js-cgi are on the same machine (most common). Use TCP when they are on separate servers.

Worker Count

The number of workers determines how many requests can be processed concurrently. A good starting point is the number of CPU cores:

# Match CPU cores
js-cgi --fastcgi /var/run/js-cgi.sock --workers $(nproc)

For I/O-heavy workloads (database queries, HTTP calls), you may benefit from 2-4x the number of cores.

Was this page helpful?