Properly type Request type for Authenticated requests and Unauthenticated requests?

Viewed 6

Currently I have a declaration file that looks like this:

import { AuthenticatedUser } from ".";

export interface AuthenticatedRequest {
  isAuthenticated: boolean;
  sid: string | null;
  locals: {
    user: AuthenticatedUser | null;
  };
}

declare global {
  namespace Express {
    export interface Request extends AuthenticatedRequest {}
  }
}

I assign these values in my middleware so I know the user will not be able to access certain routes when not authenticated. The problem is I have to do this in every route I have to use my user object:

  if (!req.locals?.user) {
    return res
      .status(StatusCodes.UNAUTHORIZED)
      .json({ message: ReasonPhrases.UNAUTHORIZED });
  }

  const { user } = req.locals;

How can I tell typescript that the user is authenticated for this route? Do I need to have a separate interface and import it into each of these files or is there a more elegant solution?

As always, thanks for your help.

0 Answers
Related