title: How to redirect to login page for restricted pages in next.js?
body: <p>In the udemy tutorial <a href="https://www.udemy.com/course/react-2nd-edition/" rel="noreferrer">The Complete React Developer Course</a> the additional package <a href="https://www.npmjs.com/package/history" rel="noreferrer">history</a> was used to get the router outside a component for redirecting when the user is not authenticated:</p>
  
  <pre><code>/* AppRouter.js */
  import createHistory from "history/createBrowserHistory";
  
  const AppRouter = () =&gt; (
      &lt;Router history={history}&gt;
        &lt;div&gt;
          &lt;Switch&gt;
              &lt;PublicRoute path="/" component={LoginPage} exact={true} /&gt;
              &lt;PrivateRoute
                  path="/dashboard"
                  component={ExpenseDashboardPage}
              /&gt;
              &lt;PrivateRoute path="/create" component={AddExpensePage} /&gt;
              &lt;PrivateRoute path="/edit/:id" component={EditExpensePage} /&gt;
              &lt;Route component={NotFoundPage} /&gt;
          &lt;/Switch&gt;
        &lt;/div&gt;
      &lt;/Router&gt;
  );
  
  export default AppRouter;
  
  
  
  /* PrivateRouter.js */
  import React from "react";
  import { connect } from "react-redux";
  import { Route, Redirect } from "react-router-dom";
  import Header from "../components/Header";
  
  export const PrivateRoute = ({
      isAuthenticated,
      component: Component,
      ...rest
  }) =&gt; (
      &lt;Route
          {...rest}
          component={(props) =&gt;
              isAuthenticated ? (
                  &lt;div&gt;
                      &lt;Header /&gt;
                      &lt;Component {...props} /&gt;
                  &lt;/div&gt;
              ) : (
                  &lt;Redirect to="/" /&gt;
              )
          }
      /&gt;
  );
  
  const mapStateToProps = (state) =&gt; ({
      isAuthenticated: !!state.auth.uid
  });
  
  export default connect(mapStateToProps)(PrivateRoute);
  </code></pre>
  
  <p>The code for <code>app.js</code> is as follows:</p>
  
  <pre><code>/* app.js */
  import AppRouter, { history } from "./routers/AppRouter";
  
  const store = configureStore();
  
  const jsx = (
      &lt;Provider store={store}&gt;
          &lt;AppRouter /&gt;
      &lt;/Provider&gt;
  );
  
  firebase.auth().onAuthStateChanged((user) =&gt; {
      if (user) {
          store.dispatch(login(user.uid));
          store.dispatch(startSetExpenses()).then(() =&gt; {
              if (history.location.pathname === "/") {
                  history.push("/dashboard");
              }
          });
      } else {
          store.dispatch(logout());
          history.push("/");
      }
  });
  
  ReactDOM.render(jsx, document.getElementById("app"));
  </code></pre>
  
  <p>My question now is, how can I achieve this in my next.js project? I have tried a kind of similar way in the <code>_app.js</code> file. Can I accomplish this behavior somehow with the <code>getInitialProps</code> routine? In the zeit/next example <a href="https://github.com/zeit/next.js/tree/canary/examples/with-firebase-authentication" rel="noreferrer">with-firebase-authentication</a> I have seen a combination of <code>getInitialProps</code> and <code>componentDidMount</code>, but was not successful to implement it in this way.</p>
  
  <pre><code>import withRedux from 'next-redux-wrapper';
  import App from 'next/app';
  import React from 'react';
  import { Provider } from 'react-redux';
  import { firebase } from '../src/firebase/firebase';
  import reduxStore from '../src/redux/store';
  
  class MyApp extends App {
    static async getInitialProps({ Component, ctx }) {
      firebase.auth().onAuthStateChanged((user) =&gt; {
        if (user) {
          console.log('log in');
        } else {
          if (ctx.isServer &amp;&amp; ctx.req.url !== '/login') {
            ctx.res.writeHead(302, { Location: '/login' });
            ctx.res.end();
          }
          console.log('log out');
        }
      });
  
      return {
        pageProps: Component.getInitialProps
          ? await Component.getInitialProps(ctx)
          : {}
      };
    }
  
    render() {
      const { Component, pageProps, store } = this.props;
  
      return (
        &lt;Provider store={store}&gt;
          &lt;Component {...pageProps} /&gt;
        &lt;/Provider&gt;
      );
    }
  }
  
  // firebase.auth().onAuthStateChanged((user) =&gt; {
  //   if (user) {
  //     console.log('log in');
  //   } else {
  //     // router instance not accessible!
  //     Router.push("/login");
  //     console.log('log out');
  //   }
  // });
  
  export default withRedux(reduxStore, { debug: false })(MyApp);
  </code></pre>