Search code examples
javascriptnode.jsloopsexpressbreadcrumbs

JavaScript - Express JS - Dynamic Breadcrumbs Creation (Name + URL)


I would like to create some middleware (Server Side) that will automatically generate breadcrumbs and pass the through to the client. I am using handlebars for a template engine and express for my routing.

Say I have a route like this:

/* GET home page. */
router.get('/services/heroku/standards', getBreadcrumbs, (req, res) => {
  res.render('index', {
    breadcrumbs: req.breadcrumbs,
  });
});

I would like to have a middleware function that goes through and gets the req.originalUrl, then with that creates a JSON Object / Array of Breadcrumbs.

I have created this function so far:

// Function for getting breadcrumbs of the page
function getBreadcrumbs(req, res, next) {
  // Initizating the JSON Object.
  const myJson = {};
  // Getting the URL and splitting the variables into an Array.
  const pathArray = req.originalUrl.split('/');
  // Removing the first value in the array as it will be empty.
  pathArray.shift();
  // Getting the length of the array.
  const arrayLength = pathArray.length;
  // Looping through the array and pushing value to the Json Object
  for (let i = 0; i < arrayLength; i++) {
    // Adding the breadcrumb name E.G home
    myJson.breadcrumbName = pathArray[i];
    // Adding the breadcrumb URL E.G /home/heroku/standards - **TROUBLE HERE!!!!!**
    myJson.breadcrumbUrl = req.originalUrl;
  }
  // Storing the array above in the request.
  req.breadcrumbs = pathArray;
  // If the request is the home page we need to change the value to: Home
  if (req.breadcrumbs[0] === '') {
    // Change the value of the first array to Home
    req.breadcrumbs[0] = 'Home';
  }
  // Finished the middleware request.
  next();
}

I was hoping for this sort of expected outcome maybe if the URL is: /services/heroku/standards.

const myJson = [
{
    breadcrumbName: "Services",
    breadcrumbUrl: "/services"
},
{
    breadcrumbName: "Heroku",
    breadcrumbUrl: "/services/heroku"
},
{
    breadcrumbName: "Standards",
    breadcrumbUrl: "/services/heroku/standards"
}

If there is a more efficient way of getting this outcome please let me know.


Solution

  • Found the answer. This will store breadcrumbs into the req.breadcrumbs

    // Function for getting breadcrumbs of the page
        function getBreadcrumbs(req, res, next) {
          const urls = req.originalUrl.split('/');
          urls.shift();
          req.breadcrumbs = urls.map((url, i) => {
            return {
              breadcrumbName: (url === '' ? 'Home' : url.charAt(0).toUpperCase() + url.slice(1)),
              breadcrumbUrl: `/${urls.slice(0, i + 1).join('/')}`,
            };
          });
          next();
        }