Session
After a user has logged in, Ory creates a session cookie that your application can use to verify the user's authentication status. This guide shows how to work with sessions in your application.
Protect routes
You can protect routes by checking for a session cookie.
- Expressjs
- Next.js
- Go
const requireAuth = async (req, res, next) => {
try {
const session = await ory.toSession({ cookie: req.header("cookie") })
req.session = session
next()
} catch (error) {
res.redirect(`${process.env.ORY_SDK_URL}/self-service/login/browser`)
}
}
app.get("/", requireAuth, (req, res) => {
res.json(req.session.identity.traits) // { email: 'newtestuser@gmail.com' }
})
./middleware.ts
import { NextResponse, NextRequest } from "next/server"
import ory from "@/lib/ory"
export async function middleware(request: NextRequest) {
try {
await ory.toSession({
cookie: request.headers.get("cookie") || "",
})
// If toSession() doesn't throw, the session is valid
return NextResponse.next()
} catch (error) {
return NextResponse.redirect(
`${process.env.ORY_SDK_URL}/self-service/login/browser`,
)
}
}
// Configure which routes to protect
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|public).*)"],
}
middleware.go
package main
import (
"context"
"errors"
"log"
"net/http"
ory "github.com/ory/client-go"
)
func (app *App) sessionMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
log.Printf("Checking authentication status\n")
// Pass cookies to Ory's ToSession endpoint
cookies := request.Header.Get("Cookie")
// Verify session with Ory
session, _, err := app.ory.FrontendAPI.ToSession(request.Context()).Cookie(cookies).Execute()
// Redirect to login if session doesn't exist or is inactive
if err != nil || (err == nil && !*session.Active) {
log.Printf("No active session, redirecting to login\n")
// Redirect to the login page
http.Redirect(writer, request, app.tunnelUrl+"/self-service/login/browser", http.StatusSeeOther)
return
}
// Add session to context for the handler
ctx := withSession(request.Context(), session)
next.ServeHTTP(writer, request.WithContext(ctx))
}
}
func withSession(ctx context.Context, v *ory.Session) context.Context {
return context.WithValue(ctx, "req.session", v)
}
func getSession(ctx context.Context) (*ory.Session, error) {
session, ok := ctx.Value("req.session").(*ory.Session)
if !ok || session == nil {
return nil, errors.New("session not found in context")
}
return session, nil
}
// Dashboard page protected by middleware
mux.Handle("/", app.sessionMiddleware(app.dashboardHandler))
Refresh sessions
You can refresh user sessions to extend their expiration time:
- Expressjs
- Next.js
- Go
app.get("/refresh-session", async (req, res) => {
// Redirect to login with refresh=true parameter
res.redirect(`${baseUrl}/ui/login?refresh=true`)
})
api/refresh-session/route.ts
import { NextResponse } from "next/server"
export async function GET() {
return NextResponse.redirect(
`${process.env.ORY_SDK_URL}/self-service/login/browser?refresh=true`,
)
}
refresh_handler.go
// refresh_handler.go
package main
import (
"net/http"
)
// RefreshSessionHandler handles the /refresh-session route
func (app *App) refreshSessionHandler(writer http.ResponseWriter, request *http.Request) {
// Redirect to Ory login UI with refresh=true parameter
http.Redirect(writer, request, app.tunnelUrl+"/self-service/login/browser?refresh=true", http.StatusSeeOther)
}
Configure session settings in Ory Console
You can configure various session-related settings through the Ory Console. Learn how to:
- Configure Session lifespan
- Allow users to access sensitive settings in their profile like changing credentials.