2017-07-06 73 views
1

我有這樣的代碼來檢查,如果用戶進行身份驗證Next.js服務器端的路由

const withAuth = AuthComponent => { 
    class Authenticated extends Component { 
    static async getInitialProps (ctx) { 
     let componentProps 
     if (AuthComponent.getInitialProps) { 
     componentProps = await AuthComponent.getInitialProps(ctx) 
     } 
     return { 
     ...componentProps 
     } 
    } 
    componentDidMount() { 
     this.props.dispatch(loggedIn()) 
    } 
    renderProtectedPages (componentProps) { 
     const { pathname } = this.props.url 
     if (!this.props.isAuthenticated) { 
     if (PROTECTED_URLS.indexOf(pathname) !== -1) { 
      // this.props.url.replaceTo('/login') 
      Router.replace('/login')     // error 
     } 
     } 
     return <AuthComponent {...componentProps} /> 
    } 
    render() { 
     const { checkingAuthState, ...componentProps } = this.props 
     return (
     <div> 
      {checkingAuthState ? (
      <div> 
       <h2>Loading...</h2> 
      </div> 
     ) : (
      this.renderProtectedPages(componentProps) 
     )} 
     </div> 
    ) 
    } 
    } 
    return connect(state => { 
    const { checkingAuthState, isAuthenticated } = state.data.auth 
    return { 
     checkingAuthState, 
     isAuthenticated 
    } 
    })(Authenticated) 
} 

它的偉大工程,但是當我嘗試將用戶重定向我得到這個錯誤:

找不到路由器實例。你應該只在你的應用的客戶端使用「next/router」。

,如果我嘗試使用this.props.url.replaceTo('/login')我得到這樣的警告

警告: 'url.replaceTo()' 已過時。使用「下一個/路由器」API。

所以這是讓我瘋狂,我想知道是否有一種方法來實現這種重定向或另一種方式來控制身份驗證在這種情況下,只是一個線索將是偉大的。

回答

0

我也想在服務器端找到解決方案。 但我通過寫入「document.location = xxx」來修復它客戶端

0

您應該檢查您的代碼是否在服務器端或客戶端執行。 這樣:

const isClient = typeof document !== 'undefined' 
isClient && Router.replace('/login') 

,並處理了服務器端的重定向,你可以簡單地使用你的服務器這樣做。 例如:

server.get("/super-secure-page", (req, res) => { 
    // Use your own logic here to know if the user is loggedIn or not 
    const token = req.cookies["x-access-token"] 
    !token && res.redirect("/login") 
    token && handle(req, res) 
}) 

只是爲了您的信息,我被這個next.js code example

啓發
相關問題