Toshio Blog

Nextjs Redirect

September 11, 2018

next.jsを使う中でリダイレクト処理を扱う方法に、サーバー側で一工夫する箇所があるのだな、と気づきがあったので記事として残しておきます。

リダイレクト処理

import Router from 'next/router'
export default (context, target) => {
if (context.res) {
// server
// 303: "See other"
context.res.writeHead(303, { Location: target })
context.res.end()
} else {
// In the browser, we just pretend like this never even happened ;)
Router.replace(target)
}
}
view raw redirect.js hosted with ❤ by GitHub

リダイレクトされた場合の扱い

if (res && res.finished) { の箇所がポイント

export default App => {
return class Hoc extends React.Component {
static async getInitialProps (ctx) {
const { Component, router, ctx: { req, res } } = ctx
let appProps = {}
if (App.getInitialProps) {
appProps = await App.getInitialProps(ctx)
}
if (res && res.finished) {
// When redirecting, the response is finished.
// No point in continuing to render
return {}
}
return {
...appProps
}
}
constructor (props) {
super(props)
}
render () {
return <App {...this.props} />
}
}
}
view raw hoc.js hosted with ❤ by GitHub

使用例

redirect({}, '/signin')
view raw sample-use.js hosted with ❤ by GitHub

引用元: https://github.com/zeit/next.js/tree/canary/examples/with-apollo-auth


Written by Ta Toshio who lives and works in Saitama, Japan .You should follow him on Twitter