Skip to content

Instantly share code, notes, and snippets.

@mkamakura
Last active November 8, 2018 10:06
Show Gist options
  • Save mkamakura/569f81b4e60cd30672887f545d372509 to your computer and use it in GitHub Desktop.
Save mkamakura/569f81b4e60cd30672887f545d372509 to your computer and use it in GitHub Desktop.
redirect login page on nextjs
/* @flow */
import React, { Component } from 'react'
import Router from 'next/router'
import { checkLogin } from '../../redux/modules/auth'
type Props = {
location: string,
}
export default ({ location }: Props) => (ComposedComponent: any) => class needLogin extends Component<Object> {
static async getInitialProps ({ res, reduxStore }: { res: any, reduxStore: any }) {
const { getState, dispatch } = reduxStore
if (res) {
await dispatch(checkLogin()).catch((e) => console.error(e))
if (!getState().app.auth.login) {
res.writeHead(302, {
Location: '/login?location=' + location
})
res.end()
}
} else {
if (!getState().app.auth.login) {
Router.push({ pathname: '/login', query: { location } })
}
}
return {}
}
render () {
return <ComposedComponent {...this.props} />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment