Next.js Discord

Discord Forum

If I set a cookie in middleware.ts is it available within server actions?

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
I'm tracking subdomains in middleware, and then in the server action using that to find the id of the tenant. Will this work as intended?

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export function middleware(req: NextRequest) {
    const host = req.headers.get("host") || "";
    const [subdomain] = host.split(".");

    if (subdomain && subdomain !== "www" && subdomain !== "ours") {
        const res = NextResponse.next();
        res.cookies.set("subdomain", subdomain, {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            sameSite: "lax",
            path: "/",
        });
        return res;
    }

    return NextResponse.next();
}

2 Replies