Search code examples
sveltesapper

Sapper: point middleware's "ignore" dirs to "_error.svelte"


I've set sapper to ignore some dirs by routes, like this:

polka()
    .use(
        sapper.middleware({
            // Exclude components from routing
            ignore: ['/admin', '/components'],
    )
    .listen(PORT);

And now, navigating browser in http://localhost:3000/admin and http://localhost:3000/components it prints single:

Not Found

Can I point those paths to regular /routes/_error.svelte with 404 error somehow?


Solution

  • The problem is, ignore literally causes Sapper to ignore the request. Internally it just calls next() when it sees one of these routes. You can get the behaviour you want by changing the route to a non-existent one:

    function handle_ignored(req, res, next) {
        if (['/admin', '/components'].some(path => req.path.startsWith(path))) {
            req.path = '/_error'; // ... or any other non-existent path
        }
        next();
    }
    
    polka()
        .use(
            handle_ignored,
            sapper.middleware()
        )
        .listen(PORT, err => {
            if (err) console.log('error', err);
        });