百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
N

next-firebase-auth

> 前端框架
开源

适用于所有 Next.js 渲染策略的简单 Firebase 身份验证

1.4K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

适用于所有 Next.js 渲染策略的简单 Firebase 身份验证

next-firebase-auth

Simple Firebase authentication for all Next.js rendering strategies.

Demo • Alternatives • Getting Started • API • Config • Types • Migrating to v1 • Examples • Troubleshooting • Contributing

What It Does

This package makes it simple to get the authenticated Firebase user and ID token during both client-side and server-side rendering (SSR).

       Support for all Next.js rendering strategies
       Signed, secure, HTTP-only cookies by default
       Server-side access to the user's Firebase ID token
       Built-in cookie management
     ↩️   Built-in support for redirecting based on the user's auth status

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.

Demo

See a live demo of the example app.

When (Not) to Use this Package

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.

  • Pros: It's simpler and removes this package as a dependency.
  • Cons: You will not have access to the Firebase user when you use 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:

  1. On the client, set a JavaScript cookie with the Firebase user information once the Firebase JS SDK loads.
    • Pros: You won't need login/logout API endpoints. You can structure the authed user data however you'd like.
    • Cons: The cookie will be unsigned and accessible to other JavaScript, making this approach less secure. You won't always have access to the Firebase ID token server side, so you won't be able to access other Firebase services. (Note that you can set the ID token in the cookie, but it will expire after an hour and be invalid for future server-side-rendered pages.)
  2. Use Firebase's session cookies.
    • Pros: It removes this package as a dependency.
    • Cons: You won't have access to the Firebase ID token server side, so you won't be able to access other Firebase services. You'll need to implement the logic for verifying the session and managing the session state.

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.

Get Started

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.

Example config:

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)

API

  • init
  • withUser
  • withUserTokenSSR
  • withUserSSR
  • useUser
  • setAuthCookies
  • unsetAuthCookies
  • verifyIdToken
  • getUserFromCookies
  • AuthAction

init(config)

Initializes next-firebase-auth, taking a config object.

  • This must before calling any other method.
  • We recommend initializing the Firebase client SDK prior to calling this.

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· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptcookiesfirebasefirebase-authenticationfirebase-js-sdk

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类前端框架
定价开源

> 相关工具

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架