shortcode - Protect NextJS pages with a authorization HOC ๐Ÿ”

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) {
this.state = {
isLoading: true,
componentDidMount() {
if (!Auth.loggedIn()) {
this.setState({ isLoading: false })
render() {
return (
{this.state.isLoading ? (
) : (
<AuthComponent {...this.props} auth={Auth} />

Hope that helps, Ryo


๐Ÿ”— This post was filed under

Blue square avatar white centered hiragana text reading Ryosuke

@Ryosuke1 years ago