hisabimbola
hisabimbola

Reputation: 306

Load routes dynamically in express js

I am building a blog like app, and posts can be created in the admin dashboard and the public user can visit a published post via the category and permalink.

I have having issues thinking about how to register the routes in my express app.

The solution I have in mind is to fetch all posts and use a for loop to register the routes on app init. The controller is pretty simple, just render the same template.

posts.forEach((post)=> {
    app.get(':' + post.category + '/:' + post.slug, renderPostGenericController);
})

Will like to vet this solution and know if there is any other better way to do this.

Upvotes: 0

Views: 419

Answers (1)

Gilad Artzi
Gilad Artzi

Reputation: 3084

You can register one route:

app.get('/post/:category/:slug', (req, res) {
    // req.params.category
    // req.params.slug
    ...
});

This way, in your route handler you'll have access to both parameters. Now you can fetch the correct post from the DB (or wherever) with the provided category and slug.

Upvotes: 3

Related Questions