Express : detect 404 errors when using multi-files route

I am kind of new on express and I struggle with 404 error detection.

I have a main file called app.js, launching the server and specifying files to handle the different requests. As an example :

const app = express();

app.use('/user', passport.authenticate('jwt', { session: false }), userRoutes);
app.use('/feedback', passport.authenticate('jwt', { session: false }), feedbackRoutes);

// Handling errors

Then, my userRoutes file contains :

const express = require('express');
const router = express.Router();

const UsersController = require('./controllers/UsersController');

router.get('/list', UsersController.listUsers);

So as I have many routes, this worked for me so far and allow a great separation of code. But now I have a problem with 404 detection, because when trying to access a route that doesn’t exist such as /test/foo, I get the generic express error which is

<!DOCTYPE html>
<html lang="en">

    <meta charset="utf-8">

    <pre>Cannot GET /test/foo </pre>


How can I change that do make a proper error management returning a json with the correct http code in the header ? I have put a log at the very beggining of my errorController.handle function but it seems we don’t even get there.

Many thanks !


you can put this in your app.js

app.get('*', (req, res) => {
    res.send('ERROR 404 - PAGE NOT FOUND')