User logout
The logout flow is used to terminate an Ory Identities session. Ory provides logout on all supported clients:
Server-rendered browser applications
To ensure that logging out is performed by the user intentionally, Ory Identities first generates a logout URL for a given Ory Session cookie. You can then open the logout URL in the browser.
The logout URL is valid for the duration of the user's session. This means that you can call the endpoint before the user decides they want to log out and cache the logout URL. You can then use the cached URL when the user performs the action required to log out, for example, accesses a designated UI element.
import { Configuration, FrontendApi } from "@ory/client"
import { Request, Response } from "express"
const frontend = new FrontendApi(
new Configuration({
basePath: "https://playground.projects.oryapis.com/",
}),
)
const route = (req: Request, res: Response) => {
frontend
.createBrowserLogoutFlow({ cookie: req.header("cookie") })
.then(({ data }) => {
console.log(data.logout_url) // The logout URL
console.log(data.logout_token) // The logout token
// You can render the logout URL like so:
// <a href="{{data.logout_url}}>Logout</a>
// Or call the logout token:
// kratos.updateLogoutFlow(data.logout_token).then(() => {
// Logged out
// })
})
}
Post-logout redirect
After a successful logout, the system redirects the browser to the address defined in the return_to
query parameter of the
logout request URL. If the parameter is omitted, the default post logout return URL is used.
To set the default post-logout return URL:
- Ory Console
- Ory CLI
Go to Branding → Browser redirects in the Ory Console and set the URL in the Post-Logout Redirect field
Run this command in the Ory CLI:
ory patch identity-config {project-id} \
--replace '/selfservice/flows/logout/after/default_browser_return_url="{return-url}"'
If an error occurs, the browser is redirected to the Error UI.
Single page application (SPA)
Similar to server-side browser applications, Ory Identities first generates a logout URL for a given Ory Session cookie. However, you can simply call the logout URL using an AJAX request.
The following example requires the Ory Tunnel.
import { Configuration, FrontendApi } from "@ory/client"
const frontend = new FrontendApi(
new Configuration({
basePath: "http://localhost:4000", // Use your local Ory Tunnel URL
baseOptions: {
withCredentials: true,
},
}),
)
export function Logout() {
const handleLogout = async () => {
try {
// Create a "logout flow" in Ory Identities
const { data: flow } = await frontend.createBrowserLogoutFlow()
// Use the received token to "update" the flow and thus perform the logout
await frontend.updateLogoutFlow({
token: flow.logout_token,
})
} catch (error) {
// The user could not be logged out
// This typically happens if the token does not match the session,
// or is otherwise malformed or missing
}
// Logout was succesful
}
return <button onClick={handleLogout}>Logout</button>
}
Native API applications
API clients (such as native mobile apps) use Ory Session Tokens. To revoke such a token, call the logout API endpoint directly.
- TypeScript
- Go
import { Configuration, FrontendApi } from "@ory/client"
const frontend = new FrontendApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
}),
)
export async function logout(token: string) {
return await frontend.performNativeLogout({
performNativeLogoutBody: {
session_token: token,
},
})
}
package frontend
import (
"context"
"fmt"
"os"
"github.com/ory/client-go"
)
type oryMiddleware struct {
ory *ory.APIClient
}
func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}
ory = client.NewAPIClient(cfg)
}
func Logout(ctx context.Context, sessionToken string) error {
_, err := ory.FrontendApi.PerformNativeLogout(ctx).
PerformNativeLogoutBody(*client.NewPerformNativeLogoutBody(sessionToken)).
Execute()
if err != nil {
return err
}
// Logout was successful
return nil
}