Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js server side routing

I have this code to check if the user is authenticated

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)
}

It works great but I'm getting this error when I try to redirect the user:

No router instance found. You should only use "next/router" inside the client side of your app.

if I try to use this.props.url.replaceTo('/login') I get this warning

Warning: 'url.replaceTo()' is deprecated. Use "next/router" APIs.

so this is making me crazy, I was wondering if there is a way to achieve this redirection or maybe another way to control the authentication in this case just a clue will be great.

like image 589
Arnold Gandarillas Avatar asked Oct 29 '22 05:10

Arnold Gandarillas


1 Answers

You should probably check if your code is executed server side or on the client. This way:

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

And to handle the redirect for the the server side, you can simply use your server to do so. For instance:

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)
})

Just for your information, I got inspired by this next.js code example

like image 122
Cyril F Avatar answered Nov 15 '22 06:11

Cyril F