Inside my server.js file on my Next 14 application I have:
// Middleware to extract tenant from subdomain
server.use((req, res, next) => {
const hostname = req.hostname;
const subdomain = hostname.split('.')[0]; // Assumes format `tenant.domain.com`
res.cookie('tenant', subdomain, {
httpOnly: false,
path: '/',
secure: true,
sameSite: 'strict',
domain: `.localhost:${port}`,
});
next();
});
and I’m trying to access that cookie on an API route
import { NextApiRequest, NextApiResponse } from 'next';
import { NextResponse } from 'next/server';
import Cookies from 'js-cookie';
type NextApiRequestWithTenant = NextApiRequest & { tenant: string };
export async function GET(req: NextApiRequestWithTenant, res: NextApiResponse) {
// Assuming middleware adds tenant to the request object
const tenant = Cookies.get('tenant');
console.log('[TENANT API]', Cookies);
return NextResponse.json({ tenant, data: 'some data' });
}
However I am getting an empty object for my cookies.
I have verified that the cookie is being set on the server.js middleware, but I’m not sure why I can’t access that cookie on my API route.
New contributor
Nicolas Sartor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.