Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heshamelmasry77/e4d0f8b955e97e85fef105c8f8e4a637 to your computer and use it in GitHub Desktop.
Save heshamelmasry77/e4d0f8b955e97e85fef105c8f8e4a637 to your computer and use it in GitHub Desktop.
ReactJS - NextJS - A HOC for wrapping NextJS pages in an authentication check. Checks for getInitialProps on the child component and runs it, so you still get SSR from the page. Also includes a user agent for Material UI.
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) {
// Ensures material-ui renders the correct css prefixes server-side
let userAgent
if (process.browser) {
userAgent = navigator.userAgent
} else {
userAgent = ctx.req.headers['user-agent']
}
// Check if Page has a `getInitialProps`; if so, call it.
const pageProps = AuthComponent.getInitialProps && await AuthComponent.getInitialProps(ctx);
// Return props.
return { ...pageProps, userAgent }
}
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>
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment