@joystick.js/node

Advanced Routes

How to define routes with custom HTTP methods and middleware in joystick.app().

If you need to implement a route that uses an HTTP method other than GET, you can use an advanced route definition.

Example Usage

Defining a Route with a Custom HTTP Method

/index.server.js

import joystick from '@joystick.js/node';

joystick.app({
  routes: {
    '/': {
      method: 'GET',
      handler: (req = {}, res = {}) => {
        return res.status(200).send('Howdy');
      },
    },
  },
});

Instead of assigning a callback function directly to your route, assign an object. On that object, specify either:

  • A single method option as a string (one of OPTIONS, HEAD, CONNECT, GET, POST, PUT, DELETE, or PATCH).
  • Or, to support multiple methods on a single route, a methods option as an array of HTTP method strings.

Your route’s callback should be assigned to the handler property. This behaves identically to a basic route definition.

Adding Route-Specific Middleware

/index.server.js

import joystick from '@joystick.js/node';
import custom_middleware from 'middleware-package';

joystick.app({
  routes: {
    '/': {
      methods: ['POST', 'PUT'],
      middleware: [
        custom_middleware,
        (req = {}, res = {}, next = {}) => {
          if (!req.body) {
            return res.redirect('/404');
          }

          next();
        },
      ],
      handler: (req = {}, res = {}) => {
        return res.status(200).send('Howdy');
      },
    },
  },
});

Advanced route definitions support a middleware array for running route-specific middleware functions before the handler() function.

API

Definition

{
  [route_path: string]: {
    method: string,
    methods: array[string],
    middleware: array[function],
    handler: (req: object, res: object) => void,
  }
}

Parameters

route_path object required
The route path as a string, assigned an object for its definition. Either method or methods must be defined for the route to register.
method string
The HTTP method for the route (one of: GET, POST, PUT, PATCH, DELETE, or OPTIONS).
methods array[string]
An array of HTTP methods as strings for the route (e.g., ['GET', 'POST']).
middleware array
An optional array of Express middleware functions to run before the route's handler() method.
handler function required
The callback function for the route. Receives the inbound req and res objects.