A discussion came up in Discord with @eastofwestern
about how one might redirect a user after a successful login using Netlify Identity (or really most other Auth Providers save Auth0 since it supports this out of the box).
@Tobbe and I noted two approaches that we felt we should share since it’s a small snippet not really a cookbook – but let us know if you think perhaps it should be part of the docs instead.:
Redirect to a Names Route
Here the user is brought to the posts
route after login.
Note: If the route you specify in navigate
is a private route to which they do not have role permission, then they will be taken to the private unauthenticated route instead.
import { useAuth } from '@redwoodjs/auth'
import { navigate, routes } from '@redwoodjs/router'
const { logIn, logOut, isAuthenticated } = useAuth()
...
const doLogIn = async () => {
await logIn()
navigate(routes.posts())
}
Redirect the user to the page they tried to access before being denied and then logging in
Also, let’s say you tried to go to /admin/posts and were challenged such that the url is
http://localhost:8910/?redirectTo=/admin/posts
Note: Redwood router will automatically inject that redirectTo
as part of denying route access.
You can do something like:
import { useAuth } from '@redwoodjs/auth'
import { navigate, useLocation } from '@redwoodjs/router'
...
const { search } = useLocation()
const parseSearch = (search) => {
const searchParams = new URLSearchParams(search)
return [...searchParams.keys()].reduce(
(params, key) => ({
...params,
[key]: searchParams.get(key),
}),
{}
)
}
const doLogIn = async ({ search }) => {
const searchKeys = parseSearch(search)
await logIn()
navigate(searchKeys.redirectTo)
}
And that will send you to the “redirectTo” you intended to view before being asked to login which in this case is /admin/posts
.
Note: parseSearch
is taken from the Redwood router package and ideally
searchKeys.redirectTo
should be checked before call navigate.