Skip to main content

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.

export const createRequireAuth = (ory, baseUrl = process.env.ORY_SDK_URL) => {
return async (req, res, next) => {
try {
const { data: session } = await ory.toSession({
cookie: req.header("cookie"),
})
req.session = session
next()
} catch (error) {
res.redirect(`${baseUrl}/self-service/login/browser`)
}
}
}

export const registerSessionRoute = (app, requireAuth) => {
app.get("/session", requireAuth, (req, res) => {
res.json(req.session.identity.traits) // { email: 'newtestuser@gmail.com' }
})
}

Refresh sessions​

You can refresh user sessions to extend their expiration time:

export const registerRefreshSessionRoute = (app, baseUrl) => {
app.get("/refresh-session", async (req, res) => {
// Redirect to login with refresh=true parameter
res.redirect(`${baseUrl}/ui/login?refresh=true`)
})
}

Configure session settings in Ory Console​

You can configure various session-related settings through the Ory Console. Learn how to: