New Ory Agent Security is now live! Claim your complimentary test drive. Get Started!

Skip to main content

createOryMiddleware()

function createOryMiddleware(options: {
forceCookieDomain?: string
forwardAdditionalHeaders?: string[]
project?: Partial<AccountExperienceConfiguration>
trustedOrigins?: string[]
}): (r: NextRequest) => Promise<NextResponse<unknown>>

Creates a Next.js middleware function that proxies requests to the Ory SDK.

The middleware serves Ory's paths on the app's origin. Use it for local development and preview deployments.

Parameters​

ParameterTypeDescription
options{ forceCookieDomain?: string; forwardAdditionalHeaders?: string[]; project?: Partial<AccountExperienceConfiguration>; trustedOrigins?: string[]; }The Ory configuration to use for the middleware.
options.forceCookieDomain?stringThe Domain attribute to set on the cookies Ory returns, for example example.com to share a session between app.example.com and api.example.com. Without it the cookies have no Domain attribute, so the browser sends them only to the host that set them. Cookies with the __Host- prefix never get a domain and stay bound to the host that set them.
options.forwardAdditionalHeaders?string[]By default headers are filtered to forward only a fixed list, which includes the browser's Origin and Sec-Fetch-* headers. If you need to forward additional headers you can use this setting to define them.
options.project?Partial<AccountExperienceConfiguration>If you want to use a specific project configuration, you can set it here. Make sure to pass the same project configuration that you pass to @ory/elements-react
options.trustedOrigins?string[]Origins this deployment serves. The middleware signs the Ory-Base-URL-Rewrite header only for a request whose origin is a valid origin that matches one of these entries; otherwise Ory uses the project's configured base URL. Required: createOryMiddleware throws when it is unset, empty, or has an invalid entry. An entry is an origin without a path. To match several origins, use * in the host as a glob. Each * matches one or more letters, digits, or hyphens within one DNS label, and never a dot. A * can't make up the whole label right before a public suffix from the Public Suffix List, such as vercel.app or com: https://*.vercel.app is rejected, https://my-app-*-my-team.vercel.app is accepted.

Returns​

The Ory Next.js middleware function

(r: NextRequest): Promise<NextResponse<unknown>>;

Parameters​

ParameterType
rNextRequest

Returns​

Promise<NextResponse<unknown>>

Example​

middleware.ts
import { createOryMiddleware } from "@ory/nextjs/middleware"

export const middleware = createOryMiddleware({
trustedOrigins: ["http://localhost:3000", "https://my-app-*-my-team.vercel.app"],
forwardAdditionalHeaders: ["authorization", "x-custom-header"],
project: {
name: "my-project",
},
})