Alter Express routes automatically upon updating the CMS

Currently, I am working on a project that utilizes NextJS with Express for server-side routing.

lib/routes/getPages

const routes = require('next-routes')();
const getEntries = require('../helpers/getEntries');

module.exports = async (app) => {
  const { items: [globalSetings] } = await getEntries({
    content_type: 'xxxxxxxx',
    include: 1,
    limit: 1,
  });

  routes
    .add('/', 'index')
    .add(`/${globalSettings.fields.blogSlug}/:slug`, 'blog');

  return routes.getRequestHandler(app);
};

server.js

const express = require('express');
const next = require('next');
const getPages = require('./lib/routes/getPages');

const app = next();

app.prepare().then(async () => {
  const server = express();
  const pageRoutes = await getPages(app);
  server.use(pageRoutes);
  server.listen(3000);
});

My concern arises when an admin changes a slug in the CMS while the app is running. It seems that I will have to restart the app for the new slug or route to take effect. Would implementing a webhook to listen for changes from the CMS and programmatically restart the app be the best solution, despite the potential overhead? Or, is there a more efficient way to handle this scenario?

Answer №1

To implement dynamic routes in express, a workaround can be utilized. In this case, the following approach is being used in a Typescript app:

  // https://github.com/expressjs/express/issues/2596
  let dynamicRouter: express.Router
  app.use(
    (req, res, next) => dynamicRouter(req, res, next),
  )

  function loadMyRoutes() {
    const newRouter = express.Router()
    const newMiddleware = // load my new middleware

    newRouter.use(newMiddleware)

    dynamicRouter = newRouter
  }

By calling loadMyRoutes() in response to a Contentful webhook, the dynamic routes can be loaded.

app.post(`/webhook`, () => {
  loadMyRoutes()
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing pagination links to trigger image changes on click

I have a javascript function that swaps the image source when clicked. I am looking to incorporate pagination links in this script. Specifically, I want to include "Previous" and "Next" text links to navigate between images. Can someone help me figure out ...

Node.js nightmare conditions

In my express application, I have two main layers. The first layer consists of modules with functions responsible for handling database queries, filesystem operations, and similar tasks. The second layer is in charge of handling requests, also referred to ...

Ways to retrieve a JSON element and incorporate it into a CSS styling

Can someone assist me in converting a JSON object for use in CSS? I've attempted to do this using Vue.js, creating a map legend with v-for to generate the legend. However, if there is an alternative method that allows me to take a JSON object and ins ...

Guide to exporting multiple schemas in a single file with Mongoose

I am facing an issue with exporting two schemas in my model js file and trying to use them in my router js file. The code I have tried is shown below. Code snippet from certification.js file(models) const mongoose = require('mongoose'); const S ...

Error: An error occurred because the program attempted to read properties of a null value, specifically the property "defaultPrevented"

There seems to be an issue with a script error involving both the bootstrap alert and my own close alert tag. I have a script set up to automatically close alerts after 2.5 seconds when certain user actions trigger them, such as creating a blog post or del ...

Ways to check requests that need authentication of the user in Express

Is it possible to test requests that require user authentication? I am currently using local passport.js in my express app and testing with Jest and Supertest. Despite researching various solutions and attempting different methods, such as supertest-sessio ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

Tips for customizing the appearance of a Material-ui Autocomplete element

I am facing an issue with my Autocomplete component that is being used in three different places on the same page, each requiring unique styling. How can I dynamically pass styling information from where the Autocomplete is rendered to its component file? ...

Only display entries with no content

When attempting to filter data from a search, all results are being displayed on the submit button even when entering 1, 2, or 3. Here is my code below. Please let me know if I am making a mistake somewhere. ...

Antialiasing in Three.js is failing to work properly on Google Chrome

When using Chrome v31, I've noticed that antialiasing doesn't seem to be working properly. There are no errors in either browser. Here is the possibly relevant code: var renderer = new THREE.WebGLRenderer( { antialias: true } ); The rendering ...

Next.js link is lacking a href tag

When I enclose my text in Link, the <a href is missing in the DOM (although the link still works). Is this good for SEO? How does an SEO robot know that there is a link? import Link from 'next/link' . . . <Link href="/about"> ...

When an object is not empty, the function Object.getOwnPropertyNames will still return an empty array

In my code, I am filling $scope.master with data from a csv file. When I populate $scope.master within the function, all the data is present. This can be observed in the log output displayed below. However, outside of the function, although $scope.master ...

Manipulating JSON data in JavaScript

Currently delving into learning JSON as required for work purposes... I am attempting to dynamically add and delete records to a JSON object... Can anyone shed some light on why I keep receiving an UNDEFINED message? Here is the code... Appreciate any as ...

Tips for utilizing a protractor ExpectedCondition by hand

Recently diving into Protractor, I'm aiming to set up an expect statement like so: expect(elementIsVisible).toBe(true); While exploring the EC (expected conditions) section in Protractor, specifically EC.visibilityOf, I find myself unsure about the ...

dual slider controls on a single webpage

I am attempting to place two different sliders on the same page. When I implement the following code for one slider, it functions correctly: <h3>Strength of Belief</h3> <div class="slidecontainer"> <div class="slider_left"> < ...

Enabling quick navigation with express and react-router

I am currently working on an express webpack react / react router app with version (^2.0.0-rc5). Within my express setup, I am using the following code: app.use(express.static(path.join(__dirname, 'dist'))); to link my react application to a spec ...

What is the process of nesting an array of objects within an existing object, and how can additional objects be added to the array if it already exists?

I have a JSON file named questions.json containing an array of objects structured like this: { "id": "2", "ques": "here is my second code ?", "quesBrief": "I can't seem to find it too.", "hashes": "#javascript , #goodlord", "author": "slowde ...

Signal for a complete 360 degree rotation of an image

Looking to enhance my 360 image rotator with an indicator that fades out after the first image. I added this function to the end of my 360.js: (function(){ if( $('#first').css('visibility','hidden')) { $('#rotat ...

Attempting to implement Vue js extensions without relying on NPM or webpack

The issue Currently, I am trying to follow the jqWidgets guidelines provided in the link below to create a dropdown box. However, the challenge I'm facing is that their setup involves using the IMPORT functionality which is restricted by my tech lead ...

Ensure that the execution of the function is completed before moving on to the next iteration within a $.each loop

While I'm not an expert in JS or jQuery, I'm currently working on coding a chat application that requires the following functionality: Retrieve conversation list through an AJAX call Display the conversations on the left side of the webpage aft ...