DEV Community

Md Robin
Md Robin

Posted on

Debugging Dynamic Cookie Validation in Express.js

When building multi-tenant applications, validating cookies per domain can be tricky. I recently worked on a project where each domain had its own cookie configuration, and I wanted to ensure the correct cookie was being read for each request.

public validateToken: RequestHandler = catchAsync(
  async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    // Extract the hostname dynamically from the request
    const host = parse(req.hostname).hostname;

    // Get the access cookie name for this domain
    const { ACCESS } = DOMAIN_COOKIE[host as keyof typeof DOMAIN_COOKIE];

    console.log('Debug Mode – Hostname:', host);

    if (!ACCESS) {
      return this.unauthorized(req, res, next);
    }

    const accessCookie = req.signedCookies[ACCESS];

    // If the access token is missing, throw an unauthorized error
    if (!accessCookie) {
      return this.unauthorized(req, res, next);
    }

    // Continue to next middleware or route
    next();
  }
);

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

Dynamic Cookie Access
Using parse(req.hostname).hostname allows you to determine which cookie to check for the current request dynamically. This is especially useful for multi-domain setups.

Early Debugging
Adding a console.log statement for the hostname helps confirm which domain the request is coming from and whether the correct cookie name is being used.

Fail Fast
Always check for missing cookies and return an unauthorized response early to prevent unauthorized access.

Why This Matters

Without this setup, your multi-domain app could mistakenly use the wrong cookie, leading to authentication errors. Dynamic validation ensures every request is verified against its intended domain configuration.

Top comments (0)