DEV Community

Discussion on: Next.js: Firebase Authentication and Middleware for API Routes

Collapse
 
theunreal profile image
Eliran Elnasi

That's great! But do you have a way to send the firebase auth token on each request (not manually)?

Collapse
 
orenaksakal profile image
Ören Aksakal • Edited

You can achieve it like so, this way every endpoint you wrap your middleware with will have access to the user's uid and email. parseCookies is from nookies package

export function withAuth(handler: any) {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    const cookies = parseCookies({ req });
    const token = cookies.token;

    if (!token) return res.status(401).end("Not authenticated");

    const { uid, email } = await auth.verifyIdToken(cookies.token);

    if (!uid || !email) {
      return res.status(401).end("Not a valid user");
    }

    return handler({ ...req, uid, email }, res);
  };
}


Enter fullscreen mode Exit fullscreen mode