next-fire-auth
v0.0.5
Published
🔥 next-fire-auth is a simple package that handles Firebase auth for Next.js SSR and CSR components
Downloads
33
Maintainers
Readme
🔥 next-fire-auth 🔥
🔥 next-fire-auth is a simple package that handles Firebase auth for Next.js SSR and CSR components
🧩 Auth Libraries are Complex - I often find myself writing my own Firebase auth because other libraries just have way too much ramp up code to get things started. When all you really need is a React context and a couple hooks.
⏲️ Save Time - Writing auth code for Firebase is repetitive, save time by just importing this package
⚙️ Configurable - I know not everyone likes to write auth the same way, so I've tried my best (and will continue improving) the flexibility of this package so we can accommodate more solutions.
Installation
To install next-fire-auth, run the following command:
npm install next-fire-auth
or with yarn.
yarn add next-fire-auth
If you do not have Firebase installed in your project, you'll need it.
npm install firebase firebase-admin
yarn add firebase firebase-admin
How to Use
- Create a ClientProviders component to hold your client side context providers
// ClientProviders.tsx
"use client";
import { NextFireAuthContextProvider } from "next-fire-auth";
export default function ClientProviders({ children }: any) {
return <NextFireAuthContextProvider>{children}</NextFireAuthContextProvider>;
}
NOTE
If you choose to not pass a config like we do above, then next-fire-auth will auto try to build a firebase_app instance using these .env variables.
# You can find these in your firebase console dashboard
# Client side required props
NEXT_PUBLIC_FIREBASE_API_KEY="..."
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN="..."
NEXT_PUBLIC_FIREBASE_PROJECT_ID="..."
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET="..."
NEXT_PUBLIC_FIREBASE_MESSENGER_ID="..."
NEXT_PUBLIC_FIREBASE_APP_ID="..."
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID="..."
# Server side required props (Firebase Admin)
FIREBASE_CLIENT_EMAIL="..."
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY...
Custom Config
If you'd like to pass in a custom config you can do that like this
"use client";
import { BaseCookieManager, NextFireAuthContextProvider } from "next-fire-auth";
export default function ClientProviders({ children }: any) {
return (
<NextFireAuthContextProvider
config={{
firebaseApp: firebase_app, // Instead of relying on env vars, you can role your own FirebaseApp object and pass it in. This is optional
loadingComponent: <span>Loading...</span>,
cookieManager: BaseCookieManager,
onPathChange: (pathname: any, user: any, router: any) => {
// This can do whatever you want, this is just an example where
// we route to specific pages based on auth status and current url.
if (user && pathname === "/login") {
router.replace("/app/dashboard");
router.refresh();
}
if (!user && pathname.startsWith("/app")) {
router.replace("/login");
router.refresh();
}
console.log(pathname);
},
}}
>
{children}
</NextFireAuthContextProvider>
);
}
NOTE
If you're going to redirect like I am in onPathChange, I recommend using replace() + refresh()
instead of push
. For some reason push still caches the old cookie value.
Why Client Providers file?
You could totally wrap your main layout.tsx with this context, but that would require adding "use client"
to your main layout. Forcing everything to CSR.
If you'd like to take advantage of SSR you should split this out into a separate client providers component and then wrap your main layout in <ClientProviders>
- Wrap your layout
import ClientProviders from "./client-providers";
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<ClientProviders>{children}</ClientProviders>
</body>
</html>
);
}
- Access your user data client side
"use client";
import { useAuthContext } from "next-fire-auth";
export default function TestClientComponent() {
const { user } = useAuthContext();
if (!user) {
return <span>No user</span>;
}
return <div>Hello {user.uid}</div>;
}
- Access your uid server side
import { useServerUser } from "next-fire-auth/server";
export default function TestServerComponent() {
const { uid } = useServerUser();
if (!uid || !uid.value) {
return <span>No UID</span>;
}
return <div>Hello {uid.value}</div>;
}
Here is the full default config
const defaultConfig: NextFireAuthConfig = {
onPathChange: (pathname, user, router) => {},
cookieManager: DefaultCookieManager,
loadingComponent: null,
firebaseApp: currentFirebaseApp,
};
Contributing
This is an open-source project, and contributions are welcome. Feel free to open an issue or submit a PR.