Skip to content

Instantly share code, notes, and snippets.

@zaverden
Created January 7, 2022 05:07
Show Gist options
  • Save zaverden/9f6579f262ac25b591dd814047e19b30 to your computer and use it in GitHub Desktop.
Save zaverden/9f6579f262ac25b591dd814047e19b30 to your computer and use it in GitHub Desktop.
import { withAuthUserTokenSSR, AuthAction, type AuthUser } from "next-firebase-auth";
import { NextApiRequest, NextApiResponse } from "next";
const checkServerSideAuth =
typeof window !== "undefined"
? () => {} // "withAuthUserTokenSSR" can only be called server-side.
: withAuthUserTokenSSR({
whenAuthed: AuthAction.RENDER,
whenUnauthed: AuthAction.REDIRECT_TO_LOGIN,
authPageURL: "401",
})(async ({ AuthUser }) => ({ AuthUser, props: {} }));
type AuthorizedApiHandler = (
req: NextApiRequest,
res: NextApiResponse,
auth: AuthUser
) => Promise<void>;
export function withAuthUserTokenAPI(handler: AuthorizedApiHandler) {
return async (req: NextApiRequest, res: NextApiResponse) => {
// @ts-expect-error wrong typings in lib. remove expect-error if typings are correct now
const { AuthUser, redirect } = await checkServerSideAuth({ req, res });
if (redirect) {
res.status(401).json({ ok: false, code: "unauthorized" });
return;
}
return handler(req, res, AuthUser);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment