fridays / next-routes

Universal dynamic routes for Next.js
MIT License
2.47k stars 230 forks source link

Protect URLS #79

Closed sstubbs closed 7 years ago

sstubbs commented 7 years ago

How do I protect urls like using react router uses onEnter?

lfades commented 7 years ago

I don't think you can, but you can use express (or something similar) for that.

const app = next({dev: true})
const handle = routes.getRequestHandler(app)

app.prepare()
.then(() => {
  const server = express()

  server.get('*', (req, res, next) => {
    // do something else...
    next()
  })

  server.get('*', (req, res) => {
    return handle(req, res)
  })
})
fridays commented 7 years ago

getInitialProps is usually a good place to do this, then it works on both server and client. Something like:

Account.getInitialProps = async () => {
  const user = await callYourApi('/authenticate')
  // Maybe send 401 error?
}