Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Created August 8, 2018 22:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/cc032c1dba57f19a11a87bc6c2e2d4f9 to your computer and use it in GitHub Desktop.
Save whoisryosuke/cc032c1dba57f19a11a87bc6c2e2d4f9 to your computer and use it in GitHub Desktop.
NextJS - (better) HOC for authenticating pages using JWT token stored in cookies. HOC checks for cookie, if it doesn't exist, user is redirected using res or Router (ideally also query API to verify token). Wrapped in an optional context provider to pass JWT down.
import React, {Component} from 'react'
import Router from 'next/router'
import TokenContext from '../context/TokenContext'
import { getCookie } from '../utils/Cookies'
import ServerRedirect from 'utils/ServerRedirect'
export default function withAuth(AuthComponent) {
return class Authenticated extends Component {
static async getInitialProps(ctx) {
const token = getCookie('yourToken', ctx.req)
// If user doesn't have a token, redirect away
if(!token)
{
if (ctx.res) {
ctx.res.writeHead(302, {
Location: 'http://example.com'
})
ctx.res.end()
} else {
Router.push('http://example.com')
}
}
// Check if Page has a `getInitialProps`; if so, call it.
const pageProps = AuthComponent.getInitialProps && await AuthComponent.getInitialProps(ctx);
// Return props.
return { ...pageProps, token }
}
render() {
return (
<TokenContext.Provider value={this.props.token}>
<AuthComponent {...this.props} />
</TokenContext.Provider>
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment