适用于所有 Next.js 渲染策略的简单 Firebase 身份验证
Simple Firebase authentication for all Next.js rendering strategies.
This package makes it simple to get the authenticated Firebase user and ID token during both client-side and server-side rendering (SSR).
We treat the Firebase JS SDK as the source of truth for auth status. When the user signs in, we call an endpoint to generate a refresh token and store the user info, ID token, and refresh token in cookies. Future requests to SSR pages receive the user info and ID token from cookies, refreshing the ID token as needed. When the user logs out, we unset the cookies.
See a live demo of the example app.
Depending on your app's needs, other approaches might work better for you.
If your app only uses static pages or doesn't need the Firebase user for SSR, use the Firebase JS SDK directly to load the user on the client side.
getServerSideProps.If your app needs the Firebase user for SSR (but does not need the ID token server side), you could consider one of these approaches:
If your app needs a generalized authentication solution—not specifically Firebase authentication—you could consider using NextAuth.js. NextAuth.js does not use Firebase authentication but supports a wide variety of identity providers, including Google. Read more here about the differences between next-firebase-auth and NextAuth.js to see which works best for your needs.
If your app uses Next.js's app router, this package does not yet support it. You can follow progress in #568.
This package will likely be helpful if you expect to use both static pages and SSR or if you need access to Firebase ID tokens server side.
A quick note on what this package does not do:
- It does not provide authentication UI. Consider firebaseui-web or build your own.
- It does not extend Firebase functionality beyond providing universal access to the authed user. Use the Firebase admin SDK and Firebase JS SDK for any other needs.
Install:
yarn add next-firebase-auth or npm i next-firebase-auth
Make sure peer dependencies are also installed:
yarn add firebase firebase-admin next react react-dom
Create a module to initialize next-firebase-auth.
See config documentation for details
…
Set the private environment variables FIREBASE_PRIVATE_KEY, COOKIE_SECRET_CURRENT, and COOKIE_SECRET_PREVIOUS in .env.local. If you have enabled the Firebase Authentication Emulator, you will also need to set the FIREBASE_AUTH_EMULATOR_HOST environment variable.
Initialize next-firebase-auth in _app.js:
// ./pages/_app.js
import initAuth from '../initAuth' // the module you created above
initAuth()
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
Create login and logout API endpoints that set auth cookies:
// ./pages/api/login
import { setAuthCookies } from 'next-firebase-auth'
import initAuth from '../../initAuth' // the module you created above
initAuth()
const handler = async (req, res) => {
try {
await setAuthCookies(req, res)
} catch (e) {
return res.status(500).json({ error: 'Unexpected error.' })
}
return res.status(200).json({ success: true })
}
export default handler
// ./pages/api/logout
import { unsetAuthCookies } from 'next-firebase-auth'
import initAuth from '../../initAuth' // the module you created above
initAuth()
const handler = async (req, res) => {
try {
await unsetAuthCookies(req, res)
} catch (e) {
return res.status(500).json({ error: 'Unexpected error.' })
}
return res.status(200).json({ success: true })
}
export default handler
Finally, use the authenticated user in a page:
// ./pages/demo
import React from 'react'
import {
useUser,
withUser,
withUserTokenSSR,
} from 'next-firebase-auth'
const Demo = () => {
const user = useUser()
return (
)
}
// Note that this is a higher-order function.
export const getServerSideProps = withUserTokenSSR()()
export default withUser()(Demo)
init(config)Initializes next-firebase-auth, taking a config object.
withUser({ ...options })(PageComponent)A higher-order function to provide the User context to a component. Use this with any Next.js page that will access the authed user via the useUser hook. Optionally, it can client-side redirect based on the user's auth status.
It accepts the following options:
| Option | Description | Default |
|---|---|---|
whenAuthed |
The action to take if the user is authenticated. One of AuthAction.RENDER or AuthAction.REDIRECT_TO_APP. |
AuthAction.RENDER |
whenAuthedBeforeRedirect |
The action to take while waiting for the browser to redirect. Relevant when the user is authenticated and whenAuthed is set to AuthAction.REDIRECT_TO_APP. One of: AuthAction.RENDER or AuthAction.SHOW_LOADER or AuthAction.RETURN_NULL. |
AuthAction.RETURN_NULL |
whenUnauthedBeforeInit |
The action to take if the user is not authenticated but the Firebase client JS SDK has not yet initialized. One of: AuthAction.RENDER, AuthAction.REDIRECT_TO_LOGIN, AuthAction.SHOW_LOADER. |
AuthAction.RENDER |
whenUnauthedAfterInit |
The action to take if the user is not authenticated and the Firebase client JS SDK has already initialized. One of: AuthAction.RENDER, AuthAction.REDIRECT_TO_LOGIN. |
AuthAction.RENDER |
appPageURL |
The redirect destination URL when we should redirect to the app. A PageURL. | config.appPageURL |
authPageURL |
The redirect destination URL when we should redirect to the login page. A PageURL. | config.authPageURL |
LoaderComponent |
The component to render when the user is unauthed and whenUnauthedBeforeInit is set to AuthAction.SHOW_LOADER. |
null |
For example, this page will redirect to the login page if the user is not authenticated:
import { withUser, AuthAction } from 'next-firebase-auth'
const DemoPage = () =>
export default withUser({
whenUnauthedAfterInit: AuthAction.REDIRECT_TO_LOGIN,
authPageURL: '/my-login-page/',
})(DemoPage)
Here's an example of a login page that shows a loader until Firebase is initialized, then redirects to the app if the user is already logged in:
import { withUser, AuthAction } from 'next-firebase-auth'
const MyLoader = () =>
const LoginPage = () =>
export default withUser({
whenAuthed: AuthAction.REDIRECT_TO_APP,
whenUnauthedBeforeInit: AuthAction.SHOW_LOADER,
whenUnauthedAfterInit: AuthAction.RENDER,
LoaderComponent: MyLoader,
})(LoginPage)
For TypeScript usage, take a look here.
withUserTokenSSR({ ...options })(getServerSidePropsFunc = ({ user }) => {})A higher-order function that wraps a Next.js pages's getServerSideProps function to provide the User context during server-side rendering. Optionally, it can server-side redirect based on the user's auth status. A wrapped function is optional; if provided, it will be called with a context object that contains an user property.
It accepts the following options:
| Option | Description | Default |
|---|---|---|
whenAuthed |
The action to take if the user is authenticated. Either AuthAction.RENDER or AuthAction.REDIRECT_TO_APP. |
AuthAction.RENDER |
whenUnauthed |
The action to |
暂无开放 Issues,或尚未同步最近议题。