Skip to content

2. Adding Routes

Eduardo Veras edited this page Jul 7, 2022 · 1 revision

There are three ways to add routes to your system.

Single route

The most basic way to create a route. Simple call the server.route with your route configuration inside the server.js file.

server.route({
	method: 'GET',
	path: '/',
	handler: async (request, reply) => {
		return reply.response({ Hello : "World!" });
	}
});

Register routes

Registering routes, allows you to separate the routes files from the server.js file. To do this, first create your route file:

route.js

"use strict";
module.exports.register = (server) => {
	server.route({
		method: 'GET',
		path: '/',
		handler: async (request, reply) => {
			return reply.response({ Hello : "World!" });
		}
	});
};

And then register the route by requiring this route.js file at the server.js file:

server.js - single route

"use strict";
const slsRouter = require('serverless-aws-router');
const server = new slsRouter.Server({});
server.register(require('route.js'));
module.exports.handler = (event, context, callback) => server.handler(event, context, callback);

If you have more than one route file, you can register using an array:

server.js - multiple routes

"use strict";
const slsRouter = require('serverless-aws-router');
const server = new slsRouter.Server({});
server.register([
	require('route1.js'),
	require('route2.js')
]);
module.exports.handler = (event, context, callback) => server.handler(event, context, callback);

Loading directory of routes

If you have several route files, under several folders and subfolders, you will find the server.loadRoutes() method very useful. Imagine that you have the following folders and files structure:

├── routes
│   ├── customers
│   │   ├── profile.js
│   │   └── salesOrders.js
│   └── invoices
│       ├── generate.js
│       └── history.js
├── server.js
└── serverless.yml

Instead, add manually every file you can do this in one line by:

"use strict";
const path = require('path');
const slsRouter = require('serverless-aws-router');
const server = new slsRouter.Server({});
server.loadRoutes(path.join(__dirname, 'routes'), { recursive : true });
module.exports.handler = (event, context, callback) => server.handler(event, context, callback);

The server.loadRoutes() will search on the routes directory for *.js files that have the register function on it (as presented at the route.js example). By default, this method will search only for routes on the same folder, but you can set the recursive: true flag to inform the loader, to search for .js route files in all sub-directories.