Expand my Community achievements bar.

How to add a redirect or 404 to a setup similar to the SPA WKND tutorial?

Avatar

Level 1

I have routing and navigation setup similar to how the WKND SPA tutorial has it:
https://experienceleague.adobe.com/docs/experience-manager-learn/getting-started-with-aem-headless/s...

And each of my components are rendered by <Route>

 

However, I'm unable to add a <Swtich> that redirects or renders a 404 page.  This is what I tried that just always renders the 404 page:

document.addEventListener('DOMContentLoaded', () => {
  ModelManager.initialize().then((pageModel) => {
    const history = createBrowserHistory();
    //Create the Redux store for the app
    const store = createStore(
      rootReducer,
      window.__REDUX_DEVTOOLS_EXTENSION__ &&
        window.__REDUX_DEVTOOLS_EXTENSION__()
    );
    render(
      <Router history={history}>
        <Provider store={store}>
          <Switch>
            <App
              history={history}
              cqChildren={pageModel[Constants.CHILDREN_PROP]}
              cqItems={pageModel[Constants.ITEMS_PROP]}
              cqItemsOrder={pageModel[Constants.ITEMS_ORDER_PROP]}
              cqPath={pageModel[Constants.PATH_PROP]}
              locationPathname={window.location.pathname}
            />
            <Route component={NotFound} />
          </Switch>
        </Provider>
      </Router>,
      document.getElementById('spa-root')
    );
  });
});

const NotFound = () => (
  <div>
    <h1>404 - Not Found!</h1>
    Go Home
  </div>
);
1 Reply

Avatar

Community Advisor

Hi @amaz2013218aw,

You can make use of ACS commons Error Handler and create error code specific pages in AEM SPA project and have text component authored within the same with respective meaningful/approved text.  (where Text component is React compatible)

https://adobe-consulting-services.github.io/acs-aem-commons/features/error-handler/index.html

 

We need not create explicit NotFound component from React standpoint. As the pages are available in AEM, we can do the error handling like we do for any other Non-SPA sites.