next-firebase-auth
Version:
Simple Firebase authentication for all Next.js rendering strategies
268 lines (264 loc) • 9.45 kB
TypeScript
// Generated by dts-bundle-generator v9.2.1
import Cookies from 'cookies';
import { User as FirebaseUser } from 'firebase/auth';
import { GetServerSideProps, GetServerSidePropsContext, NextApiRequest, NextApiResponse, PreviewData, Redirect } from 'next';
import { ParsedUrlQuery } from 'querystring';
import { ComponentType } from 'react';
export interface User {
id: string | null;
email: string | null;
emailVerified: boolean;
phoneNumber: string | null;
displayName: string | null;
photoURL: string | null;
claims: Record<string, string | boolean>;
tenantId: string | null;
getIdToken: (forceRefresh?: boolean) => Promise<string | null>;
clientInitialized: boolean;
firebaseUser: FirebaseUser | null;
signOut: () => Promise<void>;
serialize: (a?: {
includeToken?: boolean;
}) => string;
}
export type URLResolveFunction = (obj: {
ctx?: GetServerSidePropsContext<ParsedUrlQuery>;
user?: User;
}) => string | Redirect;
export type PageURL = string | Redirect | URLResolveFunction;
export type OnErrorHandler = (error: Error) => void;
export interface ConfigInput {
/**
* The redirect destination URL when redirecting to the login page.
*/
authPageURL?: PageURL;
/**
* The redirect destination URL when redirecting to the app.
*/
appPageURL?: PageURL;
/**
* The API endpoint to call on auth state change for an authenticated user.
*/
loginAPIEndpoint?: string;
/**
* The API endpoint to call on auth state change for a signed-out user.
*/
logoutAPIEndpoint?: string;
/**
* Handler called if there are unexpected errors while verifying the user's
* ID token server-side.
*/
onVerifyTokenError?: OnErrorHandler;
/**
* Handler called if there are unexpected errors while refreshing the
* user's ID token server-side.
*/
onTokenRefreshError?: OnErrorHandler;
/**
* A handler to call on auth state changes. More info:
* https://github.com/gladly-team/next-firebase-auth#tokenchangedhandler
*/
tokenChangedHandler?: (user: User) => void;
/**
* Handler called if the login API endpoint returns a non-200 response.
* Not used if a custom "tokenChangedHandler" is defined. If a handler is
* not defined, this library will throw on any non-200 responses.
*/
onLoginRequestError?: OnErrorHandler;
/**
* Handler called if the logout API endpoint returns a non-200 response. Not
* used if a custom "tokenChangedHandler" is defined. If a handler is not
* defined, this library will throw on any non-200 responses.
*/
onLogoutRequestError?: OnErrorHandler;
/**
* Whether to use application default credentials with firebase-admin.
*/
useFirebaseAdminDefaultCredential?: boolean;
/**
* The config passed to the Firebase admin SDK's `initializeApp`. Not
* required if your app manually is initializing the admin SDK elsewhere.
*/
firebaseAdminInitConfig?: {
credential: {
projectId: string;
clientEmail: string;
privateKey: string;
};
databaseURL?: string;
};
/**
* The Firebase auth emulator host address on the user's machine. Must match
* the value of the `FIREBASE_AUTH_EMULATOR_HOST` environment variable.
* https://firebase.google.com/docs/emulator-suite/connect_auth
*/
firebaseAuthEmulatorHost?: string;
/**
* The config passed to the Firebase client JS SDK's `initializeApp`.
*/
firebaseClientInitConfig: {
apiKey: string;
projectId?: string;
appId?: string;
authDomain?: string;
databaseURL?: string;
storageBucket?: string;
messagingSenderId?: string;
measurementId?: string;
};
firebaseClientAppName?: string;
tenantId?: string;
cookies: Omit<Cookies.Option & Cookies.SetOption, "sameSite"> & {
name: string;
sameSite: string;
};
/**
* When true, will log events.
*/
debug?: boolean;
}
export type UserSerialized = string;
/**
* App behavior options for when the user's auth status is pending or does not
* match the page requirements.
*/
export declare enum AuthAction {
RENDER = "render",
SHOW_LOADER = "showLoader",
RETURN_NULL = "returnNull",
REDIRECT_TO_LOGIN = "redirectToLogin",
REDIRECT_TO_APP = "redirectToApp"
}
export interface WithUserOptions {
/**
* The behavior to take if the user is authenticated.
*/
whenAuthed?: AuthAction.RENDER | AuthAction.REDIRECT_TO_APP;
/**
* The behavior to take if the user is authenticated and whenAuthed is set
* to `AuthAction.REDIRECT_TO_APP`.
*/
whenAuthedBeforeRedirect?: AuthAction.RENDER | AuthAction.SHOW_LOADER | AuthAction.RETURN_NULL;
/**
* The behavior to take if the user is not authenticated but the Firebase
* client JS SDK has not initialized.
*/
whenUnauthedBeforeInit?: AuthAction.RENDER | AuthAction.REDIRECT_TO_LOGIN | AuthAction.SHOW_LOADER | AuthAction.RETURN_NULL;
whenUnauthedAfterInit?: AuthAction.RENDER | AuthAction.REDIRECT_TO_LOGIN;
/**
* The redirect destination URL when redirecting to the app.
*/
appPageURL?: PageURL;
/**
* The redirect destination URL when redirecting to the login page.
*/
authPageURL?: PageURL;
/**
* The React component to show when the user is unauthed and
* `whenUnauthedBeforeInit` is set to `AuthAction.SHOW_LOADER`.
*/
LoaderComponent?: ComponentType | null;
}
export interface HOCProps {
userSerialized?: UserSerialized;
}
/**
* A higher-order component that provides pages with the user and, optionally,
* redirects or renders different children based on the user's current auth
* state. To access the user from SSR, this should be paired with `withUserSSR`
* or `withUserTokenSSR`.
*/
export type WithUser = <ComponentProps extends object>(options?: WithUserOptions) => (component: ComponentType<ComponentProps>) => ComponentType<ComponentProps & HOCProps>;
export interface WithUserSSROptions {
/**
* The behavior to take if the user is authenticated.
*/
whenAuthed?: AuthAction.RENDER | AuthAction.REDIRECT_TO_APP;
/**
* The behavior to take if the user is not authenticated.
*/
whenUnauthed?: AuthAction.RENDER | AuthAction.REDIRECT_TO_LOGIN;
/**
* The redirect destination URL when redirecting to the app.
*/
appPageURL?: PageURL;
/**
* The redirect destination URL when redirecting to the login page.
*/
authPageURL?: PageURL;
}
export type Dictionary<T = any> = Record<string, T>;
export type GetSSRProps<P> = P & {
userSerialized?: string;
};
export type GetSSRResult<P> = {
redirect: Redirect;
} | {
notFound: true;
} | {
props: GetSSRProps<P>;
};
export type SSRPropsContext<Q extends ParsedUrlQuery = ParsedUrlQuery, D extends PreviewData = PreviewData> = GetServerSidePropsContext<Q, D> & {
user?: User;
};
export type SSRPropsGetter<P, Q extends ParsedUrlQuery, D extends PreviewData> = (context: SSRPropsContext<Q, D>) => Promise<GetSSRResult<P>>;
/**
* An wrapper for a page's exported getServerSideProps that provides the authed
* user's info as a prop. Optionally, this handles redirects based on auth
* status.
* See this discussion on how best to use `getServerSideProps` with a
* a higher-order component pattern:
* https://github.com/vercel/next.js/discussions/10925#discussioncomment-12471
*/
export type WithUserSSR = (options?: WithUserSSROptions) => <P extends Dictionary = Dictionary, Q extends ParsedUrlQuery = ParsedUrlQuery, D extends PreviewData = PreviewData>(propGetter?: SSRPropsGetter<P, Q, D>) => GetServerSideProps<P, Q, D>;
export type UseUser = () => User;
export type GetUserFromCookiesOptions = {
/**
* An HTTP request object (for example `context.req` from the Next.js
* `context` object). It should contain the "cookie" header value.
*/
req?: NextApiRequest | GetServerSidePropsContext["req"];
/**
* Whether or not the returned user should include a Firebase ID token. When
* true, the behavior follows `withUserTokenSSR`; when false, it follows
* `withUserSSR`. Defaults to true. Read more about the distinction in
* the docs for `withUserSSR` here:
* https://github.com/gladly-team/next-firebase-auth#withuserssr-options-getserversidepropsfunc---user---
*/
includeToken?: boolean;
/**
* The value of the `next-firebase-auth` auth cookie from which to get the
* user. This is an alternative to passing the request object.
*/
authCookieValue?: string;
/**
* The `next-firebase-auth` auth cookie signature value, if using signed
* cookies. This is an alternative to passing the request object.
*/
authCookieSigValue?: string;
};
/**
* Given a request object or cookie values, verify and return
* the user. See:
* https://github.com/gladly-team/next-firebase-auth/issues/223
*/
export type GetUserFromCookies = (options: GetUserFromCookiesOptions) => Promise<User>;
export declare const getUserFromCookies: GetUserFromCookies;
export type SetAuthCookies = (req: NextApiRequest, res: NextApiResponse, options?: {
token?: string;
}) => Promise<{
idToken: string | null;
refreshToken: string | null;
user: User;
}>;
export declare const setAuthCookies: SetAuthCookies;
export type UnsetAuthCookies = (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
export declare const unsetAuthCookies: UnsetAuthCookies;
export type VerifyIdToken = (token: string, refreshToken?: string) => Promise<User>;
export declare const verifyIdToken: VerifyIdToken;
export declare const init: (config: ConfigInput) => void;
export declare const useUser: UseUser;
export declare const withUser: WithUser;
export declare const withUserSSR: WithUserSSR;
export declare const withUserTokenSSR: WithUserSSR;
export {};