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.
- Expressjs
- Next.js
- Go
// 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("/")
}
})
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)
}
After successful logout
Ory:
- Invalidates the user's session
- Removes the session cookie from the browser
- Redirects the user to the specified return URL