Skip to content

Adding a Route

Adding a new API route requires 2 steps:

  1. Add your middleware handler in /backend/middleware
  2. Add your route to the /backend/server.js file and map your middleware to it

Adding Route Middleware

StarterStack includes a convenient tool to generate new middleware based on Hygen.io.

Here is a simple example for creating a GET /hello-world route

sh
cd /backend
hygen middleware-generator new HelloWorld

This command will generate the following scaffold middleware located at /backend/middleware/helloworld/Helloworld.js

js

/**
 * uncomment if you need database functionality
 */
// const db = require('../models/index');
// const { Op } = require("sequelize");
// const { Users } = require('../models'); // <-- change this to include your Sequelize models
// const dayjs = require("dayjs");

/**
 * change the functionName below to your own name
 */

const functionName = async (req, res) => {
    const body  = req.body
    let response = {
        data: {},
    };

    try {
        /**
         * add your code here
         */

         /**
          * set your response here
          */
        response.body = null

    } catch (e) {
        res.status(500)
        response.data = { message:  e.message }
        console.log(e.message)
    }

    res.send(response)
}

/**
 * change the functionName below to to match the function name above
 */

module.exports = {
    functionName
}

Now you just need to implement your middleware logic.

Adding Your New Route

Next, open /backend/server.js and locate the section commented with

js
/**
 * import middleware
 */

Add the following somewhere in this section:

js
const  { 
   helloworld // this is the name of the middleware function you created
} = require('./middleware/helloworld/Helloworld.js');

Finally, add the route and map the middleware to it.

Towards the end of the file, add the following:

js
app.get('/hello-world', helloworld)

Adding a Protected Route

If you need a protected route, follow all the steps above but add the following to your route:

js
app.get('/hello-world', validateJWT, helloworld)

Testing Your Route

You should now be able to connect to your route using Postman or cURL or whatever tool you prefer to make http api calls.

Here is a cURL example:

sh
curl --location 'http://localhost:8000/hello-world'