404 Routing and JavaScript Frameworks

I am building a site that uses Angular 2 for its front end framework. Angular has its own 404 handler. For it to work all server side 404s need to load the index template.

(simplified, in pseudo-code)

  • My app only has one route, which renders with predefined $args

    $app->get(’/’, function($request, $response) {
    $args = [
    ‘importantStuff’ => ‘very important variables’,
    ‘title’ => ‘Some Title’,
    return $this->renderer->render($response, ‘index.phtml’, $args);

  • The user goes to http://example.com/missing, which does not exist.

  • The app needs to load index.phtml, along with the related $args, without redirecting the user (i.e. the URL will still read http://example.com/missing)

I assume I need to override the notFoundHandler function, but I do not know how to correctly add the behavior. How can I do this in Slim? Thanks.

I found a solution. The following will override notFoundHandler() which is triggered by a 404 and instead load a route without redirecting the user:

$container['notFoundHandler'] = function(\Slim\Container $container) {
    return function(\Slim\Http\Request $request, \Slim\Http\Response $response) use ($container) {
        return $container->router->getNamedRoute('index')->run($request, $response)->withStatus(404);