Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(examples): add authenticated-routes example using firebase #3669

Merged
merged 15 commits into from
Mar 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions examples/react/authenticated-routes-firebase/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Firebase Configuration: Copy this file to `.env.local` and add your Firebase credentials
# Obtain these values from your Firebase Console (see README.md for detailed setup instructions)
VITE_FIREBASE_API_KEY=
VITE_FIREBASE_AUTH_DOMAIN=
VITE_FIREBASE_PROJECT_ID=
VITE_FIREBASE_STORAGE_BUCKET=
VITE_FIREBASE_MESSAGING_SENDER_ID=
VITE_FIREBASE_APP_ID=
7 changes: 7 additions & 0 deletions examples/react/authenticated-routes-firebase/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules
.DS_Store
dist
dist-ssr
*.local
.env.*
!.env.example
11 changes: 11 additions & 0 deletions examples/react/authenticated-routes-firebase/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"files.watcherExclude": {
"**/routeTree.gen.ts": true
},
"search.exclude": {
"**/routeTree.gen.ts": true
},
"files.readonlyInclude": {
"**/routeTree.gen.ts": true
}
}
41 changes: 41 additions & 0 deletions examples/react/authenticated-routes-firebase/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Firebase Setup

1. Create a [Firebase project](https://console.firebase.google.com/)
1. By default, firebase will configure an accepted domain for localhost...update if necessary!
2. Enable Authentication in the Firebase console
3. Add GitHub as an authentication provider:

- Go to **Authentication** > **Sign-in method** > **GitHub**
- Enable GitHub authentication
- You'll need to set up OAuth in your GitHub account:
- Go to [GitHub Developer Settings](https://github.com/settings/developers)
- Create a new OAuth app
- Set the homepage URL to your local or production URL
- Set the callback URL to: `https://your-firebase-project-id.firebaseapp.com/__/auth/handler`
- Copy the Client ID and Client Secret
- Return to Firebase console and paste the GitHub Client ID and Client Secret
- Save the changes

4. Create a web app in your Firebase project:
- Go to **Project Overview** > **Add app** > **Web**
- Register the app with a nickname
- Copy the Firebase configuration object for later use

## Setup .env.local

Copy the .env.example provided and configure with your firebase credentials

````VITE_FIREBASE_API_KEY=
VITE_FIREBASE_AUTH_DOMAIN=
VITE_FIREBASE_PROJECT_ID=
VITE_FIREBASE_STORAGE_BUCKET=
VITE_FIREBASE_MESSAGING_SENDER_ID=
VITE_FIREBASE_APP_ID=```

## Run the app

To run this example:

- `npm install` or `yarn`
- `npm start` or `yarn start`
````
12 changes: 12 additions & 0 deletions examples/react/authenticated-routes-firebase/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
32 changes: 32 additions & 0 deletions examples/react/authenticated-routes-firebase/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "tanstack-router-react-example-authenticated-routes-firebase",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --port 3000",
"build": "vite build && tsc --noEmit",
"serve": "vite preview",
"start": "vite"
},
"dependencies": {
"@tanstack/react-router": "^1.112.13",
"@tanstack/router-devtools": "^1.112.13",
"@tanstack/router-plugin": "^1.112.13",
"autoprefixer": "^10.4.20",
"firebase": "^11.4.0",
"postcss": "^8.5.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"redaxios": "^0.5.1",
"simple-icons": "^14.9.0",
"tailwindcss": "^3.4.17",
"zod": "^3.24.1"
},
"devDependencies": {
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.3",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^6.1.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
72 changes: 72 additions & 0 deletions examples/react/authenticated-routes-firebase/src/auth.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import * as React from 'react'

import {
onAuthStateChanged,
type User,
type AuthProvider,
signInWithPopup,
signOut,
} from 'firebase/auth'
import { flushSync } from 'react-dom'
import { auth } from './firebase/config'

export type AuthContextType = {
isAuthenticated: boolean
isInitialLoading: boolean
login: (provider: AuthProvider) => Promise<void>
logout: () => Promise<void>
user: User | null
}

const AuthContext = React.createContext<AuthContextType | null>(null)

export function AuthContextProvider({
children,
}: {
children: React.ReactNode
}) {
const [user, setUser] = React.useState<User | null>(auth.currentUser)
const [isInitialLoading, setIsInitialLoading] = React.useState(true)
const isAuthenticated = !!user

React.useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
flushSync(() => {
setUser(user)
setIsInitialLoading(false)
})
})
return () => unsubscribe()
}, [])

const logout = React.useCallback(async () => {
console.log('Logging out...')
await signOut(auth)
setUser(null)
setIsInitialLoading(false)
}, [])

const login = React.useCallback(async (provider: AuthProvider) => {
const result = await signInWithPopup(auth, provider)
flushSync(() => {
setUser(result.user)
setIsInitialLoading(false)
})
}, [])

return (
<AuthContext.Provider
value={{ isInitialLoading, isAuthenticated, user, login, logout }}
>
{children}
</AuthContext.Provider>
)
}

export function useAuth() {
const context = React.useContext(AuthContext)
if (!context) {
throw new Error('useAuth must be used within an AuthProvider')
}
return context
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: import.meta.env.VITE_PUBLIC_FIREBASE_API_KEY,
authDomain: import.meta.env.VITE_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: import.meta.env.VITE_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_PUBLIC_FIREBASE_APP_ID,
}

// Initialize Firebase
const app = initializeApp(firebaseConfig)
export const auth = getAuth(app)
59 changes: 59 additions & 0 deletions examples/react/authenticated-routes-firebase/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createRouter } from '@tanstack/react-router'

import { routeTree } from './routeTree.gen'
import { AuthContextProvider, type AuthContextType, useAuth } from './auth'

import './styles.css'

// Set up a Router instance
const router = createRouter({
routeTree,
defaultPreload: 'intent',
scrollRestoration: true,
context: {
auth: undefined!, // This will be set after we wrap the app in AuthContextProvider
},
})

// Register things for typesafety
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}

function InnerApp() {
const auth = useAuth()

// If the provider is initially loading, do not render the router
if (auth.isInitialLoading) {
return (
<div className="flex h-screen w-full items-center justify-center p-4">
<div className="size-10 rounded-full border-4 border-gray-200 border-t-foreground animate-spin" />
</div>
)
}

return <RouterProvider router={router} context={{ auth }} />
}

function App() {
return (
<AuthContextProvider>
<InnerApp />
</AuthContextProvider>
)
}

const rootElement = document.getElementById('app')!

if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
}
50 changes: 50 additions & 0 deletions examples/react/authenticated-routes-firebase/src/posts.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import axios from 'redaxios'

async function loaderDelayFn<T>(fn: (...args: Array<any>) => Promise<T> | T) {
const delay = Number(sessionStorage.getItem('loaderDelay') ?? 0)
const delayPromise = new Promise((r) => setTimeout(r, delay))

await delayPromise
const res = await fn()

return res
}

type Invoice = {
id: number
title: string
body: string
}

let invoices: Array<Invoice> = null!

let invoicesPromise: Promise<void> | undefined = undefined

const ensureInvoices = async () => {
if (!invoicesPromise) {
invoicesPromise = Promise.resolve().then(async () => {
const { data } = await axios.get(
'https://jsonplaceholder.typicode.com/posts',
)
invoices = data.slice(0, 10)
})
}

await invoicesPromise
}

export async function fetchInvoices() {
return loaderDelayFn(() => ensureInvoices().then(() => invoices))
}

export async function fetchInvoiceById(id: number) {
return loaderDelayFn(() =>
ensureInvoices().then(() => {
const invoice = invoices.find((d) => d.id === id)
if (!invoice) {
throw new Error('Invoice not found')
}
return invoice
}),
)
}
Loading
Oops, something went wrong.