bland-finland-95044
05/09/2025, 4:11 PMbrief-egg-61061
05/09/2025, 4:11 PMbrief-egg-61061
05/09/2025, 4:11 PMtoSession()
method to verify if the user has an active session. If the session is invalid or expired, redirect the user to the login page. 2. Provide a logout mechanism that uses the Ory logout flow. Use the createBrowserLogoutFlow()
method to generate a logout URL, and direct the user to this URL to terminate their session. Here’s a practical example from the Ory documentation: jsx import React, { useEffect, useState } from "react" import { FrontendApi, Configuration, Session, Identity } from "@ory/client" const basePath = process.env.REACT_APP_ORY_URL || "<http://localhost:4000>" const ory = new FrontendApi( new Configuration({ basePath, baseOptions: { withCredentials: true, }, }), ) function App() { const [session, setSession] = useState<Session | undefined>() const [logoutUrl, setLogoutUrl] = useState<string | undefined>() useEffect(() => { ory .toSession() .then(({ data }) => { setSession(data) ory.createBrowserLogoutFlow().then(({ data }) => { setLogoutUrl(data.logout_url) }) }) .catch(() => { // Redirect to login if session is invalid/expired window.location.replace(`${basePath}/ui/login`) }) }, []) if (!session) { return <h1>Loading...</h1> } return ( <div> <p>Welcome, {session.identity.traits.email}</p> <a href={logoutUrl}>Logout</a> </div> ) } export default App
Key points: - The session is checked on load; if invalid, the user is redirected to login. - The logout link uses the Ory-generated logout URL, ensuring the session is properly terminated. This approach ensures that users are logged out both when they explicitly click "Logout" and when their session is no longer valid, providing a secure and seamless experience in your React application [Integrate authentication into React](https://www.ory.sh/docs/getting-started/integrate-auth/react#require-login-to-access-the-app-page).