You need to do what you claim doesn't work:
app.use(sessionMiddleware);
However I can guess why your attempt doesn't work. It probably comes from your misunderstanding of how Express work.
At it's core express is a middleware processing engine. You configure a list of middlewares in Express (endpoints are also middlewares, they just happen to be the last to be executed) and Express will process them one at a time in order.
The last sentence is the most important to understand: Express will process middlewares one at a time in order.
So if you do something like
app.use('/posts', postRouter);
app.use('/users', userRouter);
app.use(sessionMiddleware);
What you are doing is tell express to:
- First see if the request matches '/posts', if it does execute
postRouter
- If
postRouter
is executed see if the route call the next()
function
without any argument. If next()
is called continue processing.
- If
next()
is called with any argument stop processing and proceed
to the error handler (by default this will send an error page back to
the browser)
- If
next()
is not called stop processing
- If processing continues, second see if the request matches '/users'
if it does execute
userRouter
- If
userRouter
is executed see if the route call the next()
function
without any argument. If next()
is called continue processing.
- If
next()
is called with any argument stop processing and proceed
to the error handler
- If
next()
is not called stop processing
- If processing continues execute
sessionMiddleware
So if your flow (yes, it's a program flow, not simply API calls to Express) is like the above this means the sessionMiddleware
will not get executed for the /posts
and /users
routes.
This means you need to change your program flow as follows:
app.use(sessionMiddleware);
app.use('/posts', postRouter);
app.use('/users', userRouter);
As you can see, Express is very flexible. Say for example you want /posts
to use your session middleware but not /users
. You can do this instead:
app.use('/users', userRouter);
app.use(sessionMiddleware);
app.use('/posts', postRouter);