pico-router
pico-router copied to clipboard
Is there an example or setup for using a route guard?
Is route guard middle ware doable?
is there docs for how to write a middleware controller to all me to preload route data or check for auth etc?
Due to the large variation of authentication methods, it's difficult to provide a generalised solution. For example you could write an entire middleware dedicated to the OAuth2 OpenID Connect flow, which would act as a guard.
As a simple example which doesn't use a framework, it would look something like this:
import crayon from 'crayon'
const router = crayon.create()
const password = 'foobar'
let isAuth = false
router.use(ctx => {
if (isAuth === false) {
ctx.redirect('/login')
}
})
router.path('/', ctx => {
document.body.innerHTML = 'Hello!'
})
router.path('/login', ctx => {
const result = prompt('whats your password?')
if (result === password) {
isAuth = true
ctx.redirect('/')
}
document.body.innerHTML = 'Incorrect Password'
})
router.load()
Thanks for this. This was helpful. Even this simple example in the docs is valuable. 👍
Does this library support promise returns in the path routers so I can resolve server data before route loads?
Yes, if you return a promise in a middleware/handler, the router will wait for the promise to resolve before moving onto the next handler in the chain
Here's a sandbox with it using promises
https://codesandbox.io/s/keen-carson-hmrgh