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) {
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

๐Ÿ”— This post was filed under

Blue square avatar white centered hiragana text reading Ryosuke

@Ryosuke1 years ago