-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
chore(examples): add authenticated-routes example using firebase #3669
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
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
987c57e
Functional example of firebase client-side auth and protected routes.
downright-development b10c8e8
Adding more docs
downright-development 382ef9b
removed zustand dependency
downright-development 469c345
Removed mention of zustand as it's no longer needed
downright-development f40c18d
chore: differentiate package name
SeanCassiere c1c2e1a
chore: fix lockfile
SeanCassiere 04f6283
ci: apply automated fixes
autofix-ci[bot] 31b8f8c
fix: Updated .env to ensure only .env.example is allowed
downright-development ab7e4dd
Merge branch 'main' of github.com:downright-development/router
downright-development f735434
Fix: Updated .env.example to include instructions for firebase usage
downright-development 53878b1
fix: Updated router context, removed google and apple providers from …
downright-development 1f562cf
fix: Updated routes to use new context
downright-development 2b35141
fix: created vite.d.ts to include env vars
downright-development 15c0a3d
chore: fix lockfile
SeanCassiere e495d04
ci: apply automated fixes
autofix-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
node_modules | ||
.DS_Store | ||
dist | ||
dist-ssr | ||
*.local | ||
downright-development marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.env.* | ||
!.env.example |
11 changes: 11 additions & 0 deletions
11
examples/react/authenticated-routes-firebase/.vscode/settings.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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` | ||
```` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
6 changes: 6 additions & 0 deletions
6
examples/react/authenticated-routes-firebase/postcss.config.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
export default { | ||
plugins: { | ||
tailwindcss: {}, | ||
autoprefixer: {}, | ||
}, | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
19 changes: 19 additions & 0 deletions
19
examples/react/authenticated-routes-firebase/src/firebase/config.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
50
examples/react/authenticated-routes-firebase/src/posts.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}), | ||
) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.