Universal Router Middleware Redirects

by Vladimir Kutepov

HTML

<script src="https://unpkg.com/universal-router@4/universal-router.min.js"></script>
<script src="https://unpkg.com/history@4/umd/history.min.js"></script>
<!-- https://github.com/kriasoft/universal-router -->
<!-- https://github.com/ReactTraining/history -->

JavaScript

// import UniversalRouter from 'universal-router';
// import History from 'history';

const router = new UniversalRouter([
  { path: '', action: () => ({ content: 'Home Page' }) },
  { path: '/login', action: () => ({ content: 'Login Page' }) },
  { // middleware route
    path: '', // or '/admin' if you need to protect only admin routes
    action(context) {
      if (!context.user) {
        return { redirect: '/login', from: context.pathname  };
      }
      if (context.user.role !== 'Admin') {
        return { content: 'Access denied!' };
      }
      return context.next(); // go to child routes
    },
    children: [
      { path: '/protected', action: () => ({ content: 'Protected Page' }) },
      // ... (a lot of routes)
    ],
  },
]);

const history = History.createBrowserHistory();
function render(location) {
  router.resolve({
    pathname: location.pathname,
    user: { name: 'Jhon', role: 'Guest' },
  }).then(page => {
    if (page.redirect) {
      history.push(page.redirect, { from: page.from });
    } else {
      document.body.innerHTML = page.content;
    }
  });
}

history.listen(render);
history.replace('/protected');