Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route guards in Next.js + react

I have a have a project on Next.js and React, which doesn't use any libraries for routing. How should I implement route guards (protected routes) for non-authenticated users? Or should I just redirect them if there is no token in cookie?

like image 266
Артем Мирошниченко Avatar asked Jun 04 '18 18:06

Артем Мирошниченко


1 Answers

You can check in getInitialProps with some approp. logic evaluating the cookies to decide whether to redirect or not.

import Router from 'next/router'

const redirectToLogin = res => {  
  if (res) {
    res.writeHead(302, {Location: '/login'})
    res.end()
    res.finished = true
  } else {
    Router.push('/login')
  }
}


class ProtectedPage extends React.Component {
  static async getInitialProps ({req, res}) {
    // get cookie from req.headers or from document.cookie in browser
    // this cookie must not contain sensitive information!
    const profile = getProfileFromCookie(req)
    if (!profile) {
      redirectToLogin(res)
    }
  }
}

Have a look at this sample code https://github.com/lipp/login-with/blob/master/example/nextjs/with-profile.js#L8 (I am the author).

like image 191
lipp Avatar answered Sep 21 '22 20:09

lipp