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`,
),
)
})
import ory from "@/lib/ory"
import { redirect } from "next/navigation"
import { headers } from "next/headers"
export default async function Page() {
let session = null
try {
session = await ory.toSession({
cookie: (await headers()).get("cookie") || "",
})
} catch (error) {
redirect(`${process.env.ORY_SDK_URL}/self-service/registration/browser`)
}
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 custom URL must be allow-listed in your project's configuration;
otherwise, the request will fail. If allow-listed, 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