Routes

Introduction

Every route file must make use of the createRoute function to work correctly. The createRoute wrapper allows us to understand how to process the requests for different methods and also mutate what the file exports to work in different server/serverless environments.

Check out the routing guide on the left to understand how these files work together.

Create Route

The createRoute function can be imported from light and returns an object containing a myriad of functions. Here are the key ones you should know.

  • route: the resulting route handler that is generated by calling the other functions. Do not invoke this function, instead just export it
  • GET, POST, etc: these are route handling functions (described below) where you can specify how to respond to requests
  • useMiddleware: allows you to add middleware (described below)
const { createRoute } = require('light');
const { route, useMiddleware, GET, POST, PUT, PATCH, DELETE, ...etc } = createRoute();
// implement your methods here
module.exports = route;
// or optionally add serverless support
// module.exports = route;

Example

route

Under the hood, createRoute is a closure containing information on how to respond requests. The route variable is an object that when injected into the router when the server starts or will transform based on process.env.LIGHT_ENV.

For light to properly work, you must export this object as shown above.

GET, POST etc

Using GET, POST and other HTTP method functions will allow you to respond to requests. You may choose to implement as many methods as you want.

You must pass a function to the methods which accepts a ctx parameter (see the context docs docs) which includes keys such as req, res, send. Inside of the function you can either respond to the request using the provided send function, or you can return a string or JSON. Light uses micro under the hood to respond to requests.

useMiddleware

useMiddleware allows you to inject middleware for the route. You can also specify which methods the middleware should apply to. You may call this function as many times as you need, passing in one middleware function each time. See the middleware docs for more information.

There are additional helper functions such as withConnect which will wrap Connect based middleware (such as express middleware) which you can learn more about in the middleware docs.