Sign out
The logout flow allows users to securely terminate their sessions. This guide shows how to implement proper logout functionality in your application.
- Express (JS)
- Next.js
- Go
- Java
// Create logout route
export const registerLogoutRoute = (app, ory) => {
app.get("/logout", async (req, res) => {
try {
// Create a logout flow
const { data } = await ory.createBrowserLogoutFlow({
cookie: req.header("cookie"),
})
const logoutUrl = data.logout_url || data.logoutUrl
// Redirect to logout URL
res.redirect(logoutUrl)
} catch (err) {
res.redirect("/")
}
})
}
api/logout/route.ts
import { NextRequest, NextResponse } from "next/server"
import ory from "@/lib/ory"
export async function GET(request: NextRequest) {
try {
const { logout_url } = await ory.createBrowserLogoutFlow({
cookie: request.headers.get("cookie") || "",
})
return NextResponse.redirect(logout_url)
} catch (error) {
return NextResponse.redirect(new URL("/", request.url))
}
}
package main
import (
"log"
"net/http"
)
// LogoutHandler handles the /logout route
func (app *App) logoutHandler(writer http.ResponseWriter, request *http.Request) {
// Get cookies from the request
cookies := request.Header.Get("Cookie")
// Create a logout flow
logoutFlow, _, err := app.ory.FrontendAPI.CreateBrowserLogoutFlow(request.Context()).
Cookie(cookies).
Execute()
if err != nil {
log.Printf("Error creating logout flow: %v", err)
// Redirect to home page if there's an error
http.Redirect(writer, request, "/", http.StatusSeeOther)
return
}
// Redirect to the logout URL
http.Redirect(writer, request, logoutFlow.LogoutUrl, http.StatusSeeOther)
}
LogoutHandler.java
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sh.ory.ApiException;
import sh.ory.api.FrontendApi;
import sh.ory.model.LogoutFlow;
import java.io.IOException;
@RestController
public class LogoutHandler {
private final FrontendApi ory;
public LogoutHandler(FrontendApi ory) {
this.ory = ory;
}
@GetMapping("/logout")
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
String cookieHeader = request.getHeader("Cookie");
try {
LogoutFlow logoutFlow = ory.createBrowserLogoutFlow(cookieHeader);
String logoutUrl = logoutFlow.getLogoutUrl();
if (logoutUrl != null) {
response.sendRedirect(logoutUrl);
return;
}
} catch (ApiException e) {
// Error creating logout flow
}
// Redirect to home page if there's an error
response.sendRedirect("/");
}
}
After successful logout
- Invalidates the user's session
- Removes the session cookie from the browser
- Redirects the user to the specified return URL