Need to protect your NextJS pages behind a login? Use a HOC (higher-order component) to wrap your page components, check the #API token, and redirect users if it fails 🙅‍♂️

Bonus: You can grab things from SSR like cookies or session data using the child's getInitialProps in the HOC 🙌

import React, { Component } from "react";
import Router from "next/router";
import AuthService from "./AuthService";

export default function withAuth(AuthComponent) {
  const Auth = new AuthService("http://localhost");
  return class Authenticated extends Component {
    static async getInitialProps(ctx) {
      // Check if Page has a `getInitialProps`; if so, call it.
      const pageProps =
        AuthComponent.getInitialProps &&
        (await AuthComponent.getInitialProps(ctx));
      // Return props.
      return { ...pageProps };
    }

    constructor(props) {
      super(props);
      this.state = {
        isLoading: true,
      };
    }

    componentDidMount() {
      if (!Auth.loggedIn()) {
        Router.push("/");
      }
      this.setState({ isLoading: false });
    }

    render() {
      return (
        <div>
          {this.state.isLoading ? (
            <div>LOADING....</div>
          ) : (
            <AuthComponent {...this.props} auth={Auth} />
          )}
        </div>
      );
    }
  };
}

Hope that helps, Ryo


References

Table of Contents