Skip to content

Instantly share code, notes, and snippets.

@nwatab
Last active January 15, 2021 03:16
Show Gist options
  • Save nwatab/b65dfdab931e891ef20dd90d31c61e5d to your computer and use it in GitHub Desktop.
Save nwatab/b65dfdab931e891ef20dd90d31c61e5d to your computer and use it in GitHub Desktop.
ReactJS + Firebase + Basic Authentication (ベーシック認証)

Firebase hosting redirects to function app, then function handles basic authentication, and then function sends back SPA.

  1. npx create-react-app my-app --template typescript
  2. cd myapp && firebase init (hosting and functions)
  3. write your code
  4. Build react by npm run build
  5. mv build functions/build (functions can't access its parent directory so move build directory under functions/)
  6. mkdir dummy (firebase hosting requires directory at hosting.public in firebase.json)
  7. firebase deploy

Now your directoory structure looks like

firebase.json
src/App.tsx
dummy/
functions/src/index.ts
funnctions/built/*
import React from 'react';
import { BrowserRouter as Router, Switch, Route} from "react-router-dom";
import Users from './Users';
export default function App() {
return (
<Router>
<Switch>
<Route exact path="/users/:id">
<Users />
</Route>
</Switch>
</Router >
);
}
{
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
},
"functions": {
"predeploy": [
"npm --prefix \"$RESOURCE_DIR\" run lint",
"npm --prefix \"$RESOURCE_DIR\" run build"
],
"source": "functions"
},
"hosting": {
"public": "dummy",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "firebaseBasicAuth"
}
]
}
}
// import * as functions from "firebase-functions";
import {https} from "firebase-functions";
import basicAuth from "express-basic-auth";
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static("./build"));
app.use("*", basicAuth({users: {user: "password"}, challenge: true}));
app.get("*", (req: any, res: any) => {
// __dirname === /workspace/lib
res.sendFile("/workspace/build/index.html");
});
exports.firebaseBasicAuth = https.onRequest(app);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment