Sign up
This guide shows how to implement a secure sign up flow that authenticates users and creates sessions.
You'll learn how to:
- Redirect the user to the Ory registration page to start the sign up flow
- Redirect the user back to your application after sign up
- Check if the user is authenticated
To authenticate a user, check if the user has an active session. If the user does not have an active session, redirect the user to the Ory registration page.
- Expressjs
- Next.js
- Go
app.get("/", (req, res) => {
ory
.toSession({ cookie: req.header("cookie") })
.then((data) => res.json(data))
.catch(() =>
res.redirect(
`${process.env.ORY_SDK_URL}/self-service/registration/browser`,
),
)
})
export default function Page() {
const [session, setSession] = useState<Session | null>(null)
useEffect(() => {
// Check if the user is authenticated
const checkSession = async () => {
try {
const session = await ory.toSession()
setSession(session)
} catch (error) {
// No valid session found, redirect to Ory login
window.location.href = `${process.env.ORY_SDK_URL}/self-service/registration/browser`
}
}
checkSession()
}, [])
return (
<>
<pre>{JSON.stringify(session, null, 2)}</pre>
</>
)
}
signup_handler.go
package main
import (
"io"
"net/http"
)
// SignUpHandler handles the /signup route
func (app *App) signUpHandler(writer http.ResponseWriter, request *http.Request) {
// Get cookies from the request
cookies := request.Header.Get("Cookie")
// Try to verify session with Ory
session, response, err := app.ory.FrontendAPI.ToSession(request.Context()).Cookie(cookies).Execute()
// If there's an error or session is not active, redirect to login UI
if err != nil || (err == nil && !*session.Active) {
http.Redirect(writer, request, app.tunnelUrl+"/self-service/registration/browser", http.StatusSeeOther)
return
}
// If session is valid, send the session data as JSON response
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
// Use io.Copy to copy the response body to the writer
io.Copy(writer, response.Body)
}
You can alternatively set return_to
to a custom URL. This URL will be used as the return URL for the sign up flow:
https://$ORY_SDK_URL/self-service/registration/browser?return_to=https://example.com/dashboard