Skip to main content

Implementing user login

The login flow authenticates existing users in your application. This guide shows how to implement a secure login process that authenticates users and creates sessions.

Login flow

  1. Initialize a login flow

    Set up the SDK to communicate with your Ory instance

  2. Redirect to login UI

    Check for session and redirect to Ory login when needed

Initialize the login flow

First, set up the SDK and create a new login flow. This step contacts the Ory API to create a flow that guides users through login.

Initialize SDK

const { Configuration, FrontendApi } = require("@ory/client")

// Initialize the SDK
const basePath = process.env.ORY_SDK_URL || "http://localhost:4000"
const ory = new FrontendApi(
new Configuration({
basePath,
credentials: "include",
}),
)

Login / Register

const requireAuth = async (req, res, next) => {
try {
const { data: session } = await ory.toSession({ cookie: req.header("cookie") })
req.session = session
next()
} catch (error) {
// No valid session, redirect to login
res.redirect(`${basePath}/ui/login`)
}
}

After successful login

After a successful login, Ory:

  1. Creates a session for the user
  2. Sets a secure session cookie in the browser
  3. Redirects the user to the specified return URL or default location

Your application should then check for the presence of this session cookie to determine if a user is authenticated.

Next steps

Now that you have implemented login functionality, you should:

  1. Add session management
  2. Implement logout functionality
  3. Add password reset capabilities
  4. Explore social login options