Quick web stack for vanilla JavaScript

5 hours ago 1

Instant web stack for Node.js

-port <number> Port to listen on (default: 3000)

-ip <address> IP address to bind to (default: 127.0.0.1)

-public <path> Public directory path (default: ./public)

-api <file> Path to routes file (default: ./routes.js)

-secure Enable HTTPS (requires cert.pem and key.pem - run ./generate-certs.sh)

-help Show help message

Instaserve supports HTTPS with self-signed certificates. To enable HTTPS:

  1. Generate certificates:

    This creates cert.pem and key.pem files and adds them to your system's trust store.

  2. Run with HTTPS:

The certificate generation script:

  • Creates a self-signed certificate valid for 365 days
  • Automatically adds the certificate to your system trust store (macOS/Linux)
  • Prevents browser security warnings

The routes file (routes.js by default) defines your API endpoints. Each route is a function that handles requests to a specific URL path.

export default { // Handle GET /hello hello: (req, res, data) => { return { message: 'Hello World' } } }

Special Routes (Middleware)

Routes starting with _ are middleware functions that run on every request before the main route handler. They are useful for:

  • Logging requests
  • Authentication
  • Request modification
  • Response headers

Middleware functions can:

  • Return false to continue to the next middleware or main route
  • Return a truthy value to stop processing and use that as the response
  • Modify the request or response objects
export default { // Log every request _log: (req, res, data) => { console.log(`${req.method} ${req.url}`) return false // Continue processing }, // Block unauthorized requests _auth: (req, res, data) => { if (!data.token) { res.writeHead(401) return 'Unauthorized' } return false // Continue if authorized } }

Each route function receives:

  • req - The HTTP request object
  • res - The HTTP response object
  • data - Combined data from:
    • POST body (if JSON)
    • URL query parameters
    • Form data
// routes.js export default { // Middleware example _debug: (req, res, data) => { console.log('Request:', req.url) return false // Continue to next route }, // API endpoint api: (req, res, data) => { return { status: 'ok', data } }, // Error handling testerror: () => { throw new Error('Test error') } }
Read Entire Article