If I set a cookie in middleware.ts is it available within server actions?
Unanswered
Asiatic Lion posted this in #help-forum
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
@Asiatic Lion 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();
}
it looks like that would work, yea. However: keep in mind to check on which domain (or subdomain) the cookie is really set. Only when the cookie is visible inside your dev tools, it will be also visible within your server action
@Asiatic Lion solved?