Skip to main content

Session Management Basics

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.

Checking Session Status

You'll need to verify if a user is authenticated before allowing access to protected resources. Here's how to implement session verification:

  1. Verify the session

    Check if the user has a valid session cookie

  2. Access identity information

    Retrieve user details from the session

  3. Handle unauthenticated users

    Redirect to login if no valid session exists

Session Verification with Express.js

// Check if a user is authenticated
const requireAuth = async (req, res, next) => {
try {
// This verifies the session and throws an error if not authenticated
const { data: session } = await ory.toSession({
cookie: req.header("cookie"),
})

// Make session available to the route handler
req.session = session
next()
} catch (err) {
// Not authenticated, redirect to login
res.redirect("/login")
}
}

// Use the middleware for protected routes
app.get("/dashboard", requireAuth, (req, res) => {
// Access user data
const userId = req.session.identity.id
const email = req.session.identity.traits.email

res.render("dashboard", { user: req.session.identity })
})

Protecting Routes

Common patterns for protecting routes in your application:

// Create an authentication middleware
const requireAuth = async (req, res, next) => {
try {
const { data: session } = await ory.toSession({
cookie: req.header("cookie"),
})

req.session = session
next()
} catch (err) {
res.redirect("/login?return_to=" + encodeURIComponent(req.originalUrl))
}
}

// Apply the middleware to routes that need protection
app.get("/dashboard", requireAuth, dashboardHandler)
app.get("/settings", requireAuth, settingsHandler)
app.get("/profile", requireAuth, profileHandler)

Session Lifespans

Ory sessions have several important time properties:

PropertyDescription
issued_atWhen the session was created
authenticated_atWhen the user was authenticated
expires_atWhen the session will expire
activeWhether the session is still active

By default, sessions expire after 24 hours. This can be configured in your Ory project settings.

Refreshing Sessions

To extend a session's lifespan, you can use the session refresh flow:

app.get("/refresh-session", async (req, res) => {
try {
const { data: refreshedSession } = await ory.extendSession({
cookie: req.header("cookie"),
})

console.log("Session extended until:", refreshedSession.expires_at)
res.redirect("/dashboard")
} catch (err) {
console.error("Failed to refresh session:", err)
res.redirect("/login")
}
})

Best Practices for Session Management

  1. Always Verify Sessions: Never assume a user is authenticated without verifying their session first
  2. Use Short Expiry Times: Set shorter session lifespans for sensitive applications
  3. Implement Session Refresh: Allow users to extend their sessions when they're active
  4. Secure Cookie Handling: Always pass cookies with credentials in API requests
  5. Provide Graceful Redirects: When a session expires, save the user's intended destination and redirect there after re-authentication

Next Steps

Now that you've learned how to manage user sessions, you can:

  1. Implement Multi-factor Authentication
  2. Add Password Reset Flows
  3. Set Up Email Verification
  4. Explore OpenID Connect Integration