Unverified Commit e19023d6 authored by Hossam Magdy's avatar Hossam Magdy Committed by GitHub

Update `with-firebase-hosting[-and-typescript]` examples (#11685)

parent 943209c0
{
"projects": {
"default": "<project-name-here>"
}
}
dist/
node_modules/
# Firebase cache
.firebase/
# With Firebase Hosting and Typescript example
The goal is to host the Next.js app on Firebase Cloud Functions with Firebase Hosting rewrite rules so our app is served from our Firebase Hosting URL, with a complete Typescript stack for both the Next app and for the Firebase Functions. Each individual `page` bundle is served in a new call to the Cloud Function which performs the initial server render.
This is based off of the work of @jthegedus in the [with-firebase-hosting](https://github.com/zeit/next.js/tree/canary/examples/with-firebase-hosting) example.
If you're having issues, feel free to tag @sampsonjoliver in the [issue you create on the next.js repo](https://github.com/zeit/next.js/issues/new)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npm init next-app --example with-firebase-hosting-and-typescript with-firebase-hosting-and-typescript-app
# or
yarn create next-app --example with-firebase-hosting-and-typescript with-firebase-hosting-and-typescript-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-firebase-hosting-and-typescript
cd with-firebase-hosting-and-typescript
```
Set up firebase:
- install Firebase Tools: `npm i -g firebase-tools`
- create a project through the [firebase web console](https://console.firebase.google.com/)
- grab the projects ID from the web consoles URL: https://console.firebase.google.com/project/<projectId>
- update the `.firebaserc` default project ID to the newly created project
- login to the Firebase CLI tool with `firebase login`
#### Install project:
```bash
npm install
```
#### Run Next.js development:
```bash
npm run dev
```
#### Run Firebase locally for testing:
```
npm run serve
```
#### Deploy it to the cloud with Firebase:
```bash
npm run deploy
```
#### Clean dist folder
```bash
npm run clean
```
## Important
- The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
- `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
- The [Firebase predeploy](https://firebase.google.com/docs/cli/#predeploy_and_postdeploy_hooks) hooks defined in `firebase.json` will handle linting and compiling of the next app and the functions sourceswhen `firebase deploy` is invoked. The only scripts you should need are `dev`, `clean` and `deploy`.
- Specifying [`"engines": {"node": "8"}`](package.json#L5-L7) in the `package.json` is required for firebase functions
to be deployed on Node 8 rather than Node 6
([Firebase Blog Announcement](https://firebase.googleblog.com/2018/08/cloud-functions-for-firebase-config-node-8-timeout-memory-region.html))
. This is matched in by specifying target as `es2017` in [`src/functions/tsconfig.json`](src/functions/tsconfig) so that typescript output somewhat compacter and moderner code.
{
"functions": {
"source": "dist/functions",
"predeploy": [
"npm run lint-functions",
"npm run lint-app",
"npm run typecheck-app",
"npm run build-functions",
"npm run build-app",
"npm run copy-deps",
"npm run install-deps"
]
},
"hosting": {
"public": "dist/public",
"rewrites": [
{
"source": "**/**",
"function": "nextApp"
}
],
"predeploy": "npm run build-public"
}
}
{
"name": "with-firebase-hosting-and-typescript",
"version": "1.0.0",
"description": "Host Next.js SSR app on Firebase Cloud Functions with Firebase Hosting redirects. Built with typescript.",
"engines": {
"node": "10"
},
"scripts": {
"dev": "next src/app",
"preserve": "npm run build-public && npm run build-functions && npm run build-app && npm run copy-deps && npm run install-deps",
"serve": "cross-env NODE_ENV=production firebase serve",
"deploy": "firebase deploy",
"clean": "rimraf \"dist/functions\" && rimraf \"dist/public\"",
"build-app": "next build \"src/app\"",
"build-public": "cpx \"src/app/public/**/*.*\" \"dist/public\" -C",
"build-functions": "tsc --project src/functions",
"lint-app": "tslint --project src/app",
"typecheck-app": "tsc --project src/app",
"lint-functions": "tslint --project src/functions",
"copy-deps": "cpx \"*{package.json,package-lock.json,yarn.lock}\" \"dist/functions\" -C",
"install-deps": "cd \"dist/functions\" && npm i"
},
"dependencies": {
"firebase-admin": "^8.9.0",
"firebase-functions": "^3.1.0",
"next": "latest",
"react": "16.8.6",
"react-dom": "16.8.6"
},
"devDependencies": {
"@types/node": "12.0.12",
"@types/react": "^16.6.0",
"@types/react-dom": "16.8.4",
"cpx": "1.5.0",
"cross-env": "5.2.0",
"firebase-tools": "^7.1.0",
"rimraf": "2.6.2",
"tslint": "^5.11.0",
"tslint-react": "^3.6.0",
"typescript": "^3.2.0"
}
}
import Header from './Header'
const App = ({ children }: { children?: any }) => (
<main>
<Header />
{children}
</main>
)
export default App
import Link from 'next/link'
export default ({ pathname }: { pathname?: any }) => (
<header>
<Link href="/">
<a className={pathname === '/' ? 'is-active' : ''}>Home</a>
</Link>
<Link href="/about">
<a className={pathname === '/about' ? 'is-active' : ''}>About</a>
</Link>
</header>
)
/// <reference types="next" />
/// <reference types="next/types/global" />
import App from '../components/App'
export default () => (
<App>
<p>About Page</p>
</App>
)
import App from '../components/App'
export default () => (
<App>
<p>Index Page</p>
</App>
)
{
"compileOnSave": false,
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"allowJs": false,
"jsx": "preserve",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"noImplicitAny": false,
"strict": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"skipLibCheck": true,
"sourceMap": true,
"noEmit": true,
"lib": ["es6", "dom", "es2016"],
"baseUrl": ".",
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}
{
"extends": ["tslint:latest", "tslint-react"],
"rules": {
"quotemark": [true, "single"],
"no-submodule-imports": false
}
}
import * as functions from 'firebase-functions'
import next from 'next'
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev, conf: { distDir: 'next' } })
const handle = app.getRequestHandler()
export const nextApp = functions.https.onRequest((req, res) => {
console.log('File: ' + req.originalUrl)
return app.prepare().then(() => handle(req, res))
})
{
"compilerOptions": {
"lib": ["es6", "dom", "es2016"],
"module": "commonjs",
"strict": true,
"outDir": "../../dist/functions",
"sourceMap": true,
"target": "es2017",
"baseUrl": "./",
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true
},
"compileOnSave": true
}
{
"rules": {
// -- Strict errors --
// These lint rules are likely always a good idea.
// Force function overloads to be declared together. This ensures readers understand APIs.
"adjacent-overload-signatures": true,
// Do not allow the subtle/obscure comma operator.
"ban-comma-operator": true,
// Do not allow internal modules or namespaces . These are deprecated in favor of ES6 modules.
"no-namespace": true,
// Do not allow parameters to be reassigned. To avoid bugs, developers should instead assign new values to new vars.
"no-parameter-reassignment": true,
// Force the use of ES6-style imports instead of /// <reference path=> imports.
"no-reference": true,
// Do not allow type assertions that do nothing. This is a big warning that the developer may not understand the
// code currently being edited (they may be incorrectly handling a different type case that does not exist).
"no-unnecessary-type-assertion": true,
// Disallow nonsensical label usage.
"label-position": true,
// Disallows the (often typo) syntax if (var1 = var2). Replace with if (var2) { var1 = var2 }.
"no-conditional-assignment": true,
// Disallows constructors for primitive types (e.g. new Number('123'), though Number('123') is still allowed).
"no-construct": true,
// Do not allow super() to be called twice in a constructor.
"no-duplicate-super": true,
// Do not allow the same case to appear more than once in a switch block.
"no-duplicate-switch-case": true,
// Do not allow a variable to be declared more than once in the same block. Consider function parameters in this
// rule.
"no-duplicate-variable": [true, "check-parameters"],
// Disallows a variable definition in an inner scope from shadowing a variable in an outer scope. Developers should
// instead use a separate variable name.
"no-shadowed-variable": true,
// Empty blocks are almost never needed. Allow the one general exception: empty catch blocks.
"no-empty": [true, "allow-empty-catch"],
// Functions must either be handled directly (e.g. with a catch() handler) or returned to another function.
// This is a major source of errors in Cloud Functions and the team strongly recommends leaving this rule on.
"no-floating-promises": true,
// Do not allow any imports for modules that are not in package.json. These will almost certainly fail when
// deployed.
"no-implicit-dependencies": true,
// The 'this' keyword can only be used inside of classes.
"no-invalid-this": true,
// Do not allow strings to be thrown because they will not include stack traces. Throw Errors instead.
"no-string-throw": true,
// Disallow control flow statements, such as return, continue, break, and throw in finally blocks.
"no-unsafe-finally": true,
// Do not allow variables to be used before they are declared.
"no-use-before-declare": true,
// Expressions must always return a value. Avoids common errors like const myValue = functionReturningVoid();
"no-void-expression": [true, "ignore-arrow-function-shorthand"],
// Disallow duplicate imports in the same file.
"no-duplicate-imports": true,
// -- Strong Warnings --
// These rules should almost never be needed, but may be included due to legacy code.
// They are left as a warning to avoid frustration with blocked deploys when the developer
// understand the warning and wants to deploy anyway.
// Warn when an empty interface is defined. These are generally not useful.
"no-empty-interface": { "severity": "warning" },
// Warn when an import will have side effects.
"no-import-side-effect": { "severity": "warning" },
// Warn when variables are defined with var. Var has subtle meaning that can lead to bugs. Strongly prefer const for
// most values and let for values that will change.
"no-var-keyword": { "severity": "warning" },
// Prefer === and !== over == and !=. The latter operators support overloads that are often accidental.
"triple-equals": { "severity": "warning" },
// Warn when using deprecated APIs.
"deprecation": { "severity": "warning" },
// -- Light Warnigns --
// These rules are intended to help developers use better style. Simpler code has fewer bugs. These would be "info"
// if TSLint supported such a level.
// prefer for( ... of ... ) to an index loop when the index is only used to fetch an object from an array.
// (Even better: check out utils like .map if transforming an array!)
"prefer-for-of": { "severity": "warning" },
// Warns if function overloads could be unified into a single function with optional or rest parameters.
"unified-signatures": { "severity": "warning" },
// Prefer const for values that will not change. This better documents code.
"prefer-const": { "severity": "warning" },
// Multi-line object liiterals and function calls should have a trailing comma. This helps avoid merge conflicts.
"trailing-comma": { "severity": "warning" }
},
"defaultSeverity": "error"
}
dist/ node_modules/
# NextJs build
.next/
# Firebase cache # Firebase cache
.firebase/ .firebase/
\ No newline at end of file
# With Firebase Hosting example # with Firebase Hosting example
The goal is to host the Next.js app on Firebase Cloud Functions with Firebase Hosting rewrite rules so our app is served from our Firebase Hosting URL. Each individual `page` bundle is served in a new call to the Cloud Function which performs the initial server render. The goal is to host the Next.js app on Firebase Cloud Functions with Firebase Hosting rewrite rules so our app is served from our Firebase Hosting URL. Each individual `page` bundle is served in a new call to the Cloud Function which performs the initial server render.
This is based off of the work at https://github.com/geovanisouza92/serverless-firebase & https://github.com/jthegedus/firebase-functions-next-example as described [here](https://medium.com/@jthegedus/next-js-on-cloud-functions-for-firebase-with-firebase-hosting-7911465298f2). If you are having issues, feel free to tag @jthegedus in the [issue you create on the next.js repo](https://github.com/zeit/next.js/issues/new)
If you're having issues, feel free to tag @jthegedus in the [issue you create on the next.js repo](https://github.com/zeit/next.js/issues/new) <details>
<summary><b>Make sure that firebase is set up and you have the projectID</b></summary>
- Install Firebase Tools: `npm i -g firebase-tools`
- Create a project through the [firebase web console](https://console.firebase.google.com/)
- Login to the Firebase CLI tool with `firebase login`
- Grab the **projectID** from [`firebase projects:list`](https://firebase.google.com/docs/cli#admin-commands) or the web consoles URL: `https://console.firebase.google.com/project/<projectID>`
</details>
## How to use ## How to use
...@@ -18,8 +25,9 @@ npm init next-app --example with-firebase-hosting with-firebase-hosting-app ...@@ -18,8 +25,9 @@ npm init next-app --example with-firebase-hosting with-firebase-hosting-app
yarn create next-app --example with-firebase-hosting with-firebase-hosting-app yarn create next-app --example with-firebase-hosting with-firebase-hosting-app
``` ```
<details> Update `.firebaserc`: adding your firebase project ID
<summary><b>Download manually</b></summary>
### Download manually
Download the example: Download the example:
...@@ -28,78 +36,62 @@ curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 ...@@ -28,78 +36,62 @@ curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2
cd with-firebase-hosting cd with-firebase-hosting
``` ```
</details> Update `.firebaserc`: adding your firebase project ID
<details>
<summary><b>Set up firebase</b></summary>
- install Firebase Tools: `npm i -g firebase-tools`
- create a project through the [firebase web console](https://console.firebase.google.com/)
- grab the projects ID from the web consoles URL: `https://console.firebase.google.com/project/<projectId>`
- update the `.firebaserc` default project ID to the newly created project
- login to the Firebase CLI tool with `firebase login`
</details> Install it and run:
<details>
<summary><b>Install Project</b></summary>
```bash ```bash
npm install npm install
```
#### Run Next.js development:
```bash
npm run dev npm run dev
``` # or
yarn
#### Run Firebase locally for testing: yarn dev
``` # to run Firebase locally for testing:
npm run serve npm run serve
```
#### Deploy it to the cloud with Firebase:
```bash # to deploy it to the cloud with Firebase:
npm run deploy npm run deploy
``` ```
#### Clean dist folder ## Typescript
```bash To use Typescript, simply follow [Typescript setup](https://nextjs.org/learn/excel/typescript/setup) as normal (package.json scripts are already set).
npm run clean
```
</details> i.e: `npm install --save-dev typescript @types/react @types/node`
## Important Then you can create components and pages in `.tsx` or `.ts`
- The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL. **Only `src/next.config.js` and `firebaseFunctions.js` must remain in `*.js` format.**
- `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
- Specifying [`"engines": {"node": "8"}`](package.json#L5-L7) in the `package.json` is required for firebase functions
to be deployed on Node 8 rather than Node 6
([Firebase Blog Announcement](https://firebase.googleblog.com/2018/08/cloud-functions-for-firebase-config-node-8-timeout-memory-region.html))
. This is matched in [`src/functions/.babelrc`](src/functions/.babelrc) so that babel output somewhat compacter and moderner code.
### Customization ## Good to know
Next App and Next Server development are separated into two different folders: - [`firebase.json`](firebase.json:#L7) outlines the catchall rewrite rule for our Cloud Function.
- The empty `public/.gitignore` file is to ensure `public/` dir exists as it is required for Firebase Hosting. It is [configured](firebase.json:#L4) (by [default](https://firebase.google.com/docs/hosting/full-config#ignore)) that dotfiles (`public/.*`) are ignored from bein publicly served.
- The Cloud Function is named `nextjsFunc` (changeable in [firebaseFunctions.js](firebaseFunctions.js#L16) and [firebase.json](firebase.json#L8)).
- `public/*` files are statically served through [Firebase hosting](https://firebase.google.com/docs/hosting/full-config#public), not through [NextJs server](https://nextjs.org/docs/basic-features/static-file-serving).
- Specifying [`"engines": {"node": "10"}`](package.json#L5-L7) in `package.json` is required and the [latest supported](https://firebase.google.com/docs/functions/manage-functions#set_nodejs_version) by firebase functions.
- app - `src/app/` #### Customization
- server - `src/functions/`
If you wish to modify any configuration of the Next App, you should only modify the contents of `src/app`. Next App is in `src/` directory.
For instance, the `.babelrc` in `src/functions` is used only to compile the Firebase Cloud Functions code, which is our the Next Server code. If you wish to customize the `.babelrc` for the Next App compilation, then you should create one at `src/app/.babelrc` and follow the [customization guide](https://github.com/zeit/next.js#customizing-babel-config). The crucial files for the setup:
### \_app.js - `.firebaserc`
- `firebase.json`
- `firebaseFunctions.js`
- `src/next.config.js`
- In `package.json`: `firebase-*` packages and `engines` field
If using `_app.js` you may receive the following error on your deployed Cloud Function: ## Caveat
``` Because firebase functions require `"engines": {"node": "10"}` (or 8) to be specified (in `package.json`), if you are using `yarn` (instead of `npm`), you will need to add flag [`--ignore-engines`](https://classic.yarnpkg.com/en/docs/cli/install/#toc-yarn-install-ignore-engines).
{ Error: Cannot find module '@babel/runtime/regenerator'...
``` ## References
Despite next.js having `@babel/runtime` as a dependency, you must install it as a dependency directly in this project. - [geovanisouza92/serverless-firebase](https://github.com/geovanisouza92/serverless-firebase) repo
- [jthegedus/firebase-functions-next-example](https://github.com/jthegedus/firebase-functions-next-example) repo
- [this medium article](https://medium.com/@jthegedus/next-js-on-cloud-functions-for-firebase-with-firebase-hosting-7911465298f2)
- [Crash Course: Node.js apps on Firebase Hosting](https://youtu.be/LOeioOKUKI8)
- [Official documentation](https://firebase.google.com/docs/cli).
{ {
"hosting": { "hosting": {
"public": "dist/public", "public": "public",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"rewrites": [ "rewrites": [
{ {
"source": "**/**", "source": "**",
"function": "next" "function": "nextjsFunc"
} }
] ]
}, },
"functions": { "functions": {
"source": "dist/functions" "source": ".",
"predeploy": [
"npm --prefix \"$PROJECT_DIR\" install",
"npm --prefix \"$PROJECT_DIR\" run build"
]
} }
} }
const { join } = require('path')
const { https } = require('firebase-functions')
const { default: next } = require('next')
const isDev = process.env.NODE_ENV !== 'production'
const nextjsDistDir = join('src', require('./src/next.config.js').distDir)
const nextjsServer = next({
dev: isDev,
conf: {
distDir: nextjsDistDir,
},
})
const nextjsHandle = nextjsServer.getRequestHandler()
exports.nextjsFunc = https.onRequest((req, res) => {
return nextjsServer.prepare().then(() => nextjsHandle(req, res))
})
{ {
"name": "with-firebase-hosting", "name": "with-firebase-hosting",
"version": "4.0.1", "version": "5.0.0",
"description": "Host Next.js SSR app on Firebase Cloud Functions with Firebase Hosting redirects.", "description": "Host Next.js SSR app on Firebase Cloud Functions with Firebase Hosting redirects.",
"engines": { "engines": {
"node": "8" "node": "10"
}, },
"main": "firebaseFunctions.js",
"scripts": { "scripts": {
"dev": "next \"src/app/\"", "dev": "next src/",
"preserve": "npm run build-public && npm run build-funcs && npm run build-app && npm run copy-deps && npm run install-deps", "build": "next build src/",
"serve": "cross-env NODE_ENV=production firebase serve", "start": "next start src/",
"predeploy": "npm run build-public && npm run build-funcs && npm run build-app && npm run copy-deps", "serve": "npm run build && firebase emulators:start --only functions,hosting",
"deploy": "NODE_ENV=production firebase deploy", "shell": "npm run build && firebase functions:shell",
"clean": "rimraf \"dist/functions/**\" && rimraf \"dist/public\"", "deploy": "firebase deploy --only functions,hosting",
"build-public": "cpx \"src/app/public/**/*.*\" \"dist/public\" -C", "logs": "firebase functions:log"
"build-funcs": "babel \"src/functions\" --out-dir \"dist/functions\"",
"build-app": "next build \"src/app/\"",
"copy-deps": "cpx \"*{package.json,package-lock.json,yarn.lock}\" \"dist/functions\" -C",
"install-deps": "cd \"dist/functions\" && npm i"
}, },
"dependencies": { "dependencies": {
"firebase-admin": "^8.9.0", "firebase-admin": "^8.9.0",
"firebase-functions": "^2.1.0", "firebase-functions": "^3.3.0",
"grpc": "^1.22.2", "next": "^9.3.4",
"next": "latest", "react": "^16.13.1",
"react": "^16.7.0", "react-dom": "^16.13.1"
"react-dom": "^16.7.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/cli": "^7.2.0",
"cpx": "^1.5.0",
"cross-env": "^5.2.0",
"firebase-functions-test": "^0.1.6", "firebase-functions-test": "^0.1.6",
"firebase-tools": "^6.1.0", "firebase-tools": "^8.0.1"
"rimraf": "^2.6.0"
} }
} }
module.exports = {
distDir: '../../dist/functions/next',
}
{
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": "8.14"
}
}
]
]
}
\ No newline at end of file
const path = require('path')
const functions = require('firebase-functions')
const next = require('next')
var dev = process.env.NODE_ENV !== 'production'
var app = next({
dev,
conf: { distDir: `${path.relative(process.cwd(), __dirname)}/next` },
})
var handle = app.getRequestHandler()
exports.next = functions.https.onRequest((req, res) => {
console.log('File: ' + req.originalUrl) // log the page.js file that is being requested
return app.prepare().then(() => handle(req, res))
})
module.exports = { module.exports = {
distDir: '../../dist/functions/next', distDir: '../.next',
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment