Implementing user logout
The logout flow allows users to securely terminate their sessions. This guide shows how to implement proper logout functionality in your application.
- JavaScript/Node.js
- React
- Next.js
- Go
- cURL
// Create logout route
app.get("/logout", async (req, res) => {
try {
// Create a logout flow
const { logout_url } = await ory.createBrowserLogoutFlow({
cookie: req.header("cookie"),
})
// Redirect to logout URL
res.redirect(logout_url)
} catch (err) {
res.redirect("/")
}
})
import { useEffect } from "react"
import { ory } from "../lib/ory"
export const Logout = () => {
useEffect(() => {
// Create a logout flow and redirect to it
ory
.createBrowserLogoutFlow()
.then(({ data }) => {
// Redirect to the logout URL which will destroy the session
window.location.href = data.logout_url
})
.catch((err) => {
console.error("Logout error:", err)
// Already logged out or error, redirect to login
window.location.href = "/login"
})
}, [])
return <div>Logging out...</div>
}
package main
import (
"context"
"net/http"
ory "github.com/ory/client-go"
)
func logoutHandler(w http.ResponseWriter, r *http.Request) {
// Initialize the Ory client
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "https://$PROJECT_SLUG.projects.oryapis.com",
},
}
client := ory.NewAPIClient(configuration)
// Create a logout flow
cookie := r.Header.Get("Cookie")
flow, _, err := client.FrontendApi.CreateBrowserLogoutFlow(context.Background()).Cookie(cookie).Execute()
if err != nil {
// Already logged out or error, redirect to login
http.Redirect(w, r, "/login", http.StatusFound)
return
}
// Redirect to logout URL
http.Redirect(w, r, flow.LogoutUrl, http.StatusFound)
}
# Create a logout flow
curl -X GET \
'https://$PROJECT_SLUG.projects.oryapis.com/self-service/logout/browser' \
-H 'Accept: application/json' \
-H 'Cookie: ory_session_YOUR_PROJECT=YOUR_SESSION_COOKIE' \
--verbose
# The response contains a logout_url that you'll need to redirect the user to
After successful logout
Ory:
- Invalidates the user's session
- Removes the session cookie from the browser
- Redirects the user to the specified return URL