My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

What's the best structure for public and authenticated routes in express.js

Anthony Young's photo
Anthony Young
·Dec 3, 2018

I currently have a MVC (Model, View, Controller) like setup in my backend express.js app just serving an API and the issue I have come up against now is separating out the public routes and the private routes while keeping the structure below:

app.js -controllers --itemController.js -models --itemModel.js -routes --itemRoutes.js

In my app.js file I am pulling in these and combining them like so:

//GET THE MONGODB MODEL
const Items = require('./models/itemModel');

//GET THE ROUTE - which contains the CRUD methods
const itemRouter = require('./routes/itemRoutes')(Items);
//SET THE ROUTE AND CHECK IT IS AUTHED ON EACH REQUEST
app.use('/api/items', checkAuth, itemRouter);

I want all to be private apart from the get method: GET - /api/items - Public POST - /api/items - Private etc

Would love to see how others deal with this or a better structure?