Search code examples
node.jsexpressloopbackjs

How to define custom error page in loopback?


I want to define custom 404 not found response pages with loopback. In documentation it's been given that loopback's middleware has been defined on express but i am not getting how to define custom error page in loopback.


Solution

  • Inside the middleware.json, remove the loopback#urlNotFound middleware from the final phase and update it with this:

    "final": {
        "./middleware/url-not-found-handler": {}
    },
    

    Now, place the following content on the file server/middleware/url-not-found-handler.js

    'use strict';
    module.exports = function () {
        //4XX - URLs not found
        return function customRaiseUrlNotFoundError(req, res, next) {
            res.sendFile('path to 404.html', function (err) {
                if (err) {
                    console.error(err);
                    res.status(err.status).end();
                }
            });
        };
    };