Giter VIP home page Giter VIP logo

jthegedus / firebase-functions-next-example Goto Github PK

View Code? Open in Web Editor NEW
222.0 17.0 24.0 778 KB

Host a Next.js SSR React app on Cloud Functions for Firebase with Firebase Hosting

Home Page: https://codeburst.io/next-js-on-cloud-functions-for-firebase-with-firebase-hosting-7911465298f2

License: Other

JavaScript 90.71% HTML 9.29%
ssr server-rendering universal nextjs firebase firebase-hosting firebase-functions node

firebase-functions-next-example's Introduction


Next.js SSR app on Cloud Functions for Firebase with Firebase Hosting

Host a Next.js SSR React app on Cloud Functions for Firebase with Firebase Hosting.

Here is the accompanying Medium PostA new post is being written to describe the new project structure, Firebase partial deployments, Firebase support of pre/post-deploy hooks and what problems these new features solve.

styled with Prettier

Why?

Host your SSR Next.js app on Cloud Functions enabling a low-cost, auto-scaling SSR app experience leveraging Firebase's sweet developer experience.

How?

Firebase Hosting can rewrite routes to a Cloud Function that serves our Server-side Rendered Next.js app. Using a rewrite rule that catches ALL routes we can then host our SSR app on our Firebase Hosting URL instead of the Firebase Cloud Function URL.

instead of:

https://us-central1-<project-name>.cloudfunctions.net/<function-name>

we can use:

<project-name>.firebaseapp.com/

Next.js can then be used to achieve SSR React with Hot-Module Reloading, server and client-side routing, route level code-splitting, route prefetching and more!

A number of issues with Hosting SSR on Firebase were overcome with this method. Please refer to the Medium Post before creating issues here.

Important!

  • This example uses firebase-tools as a devDependency which is run from the node_modules/.bin/ folder via yarn. Yarn will run scripts from either the package.json or binary scripts from node_modules/.bin/. npm run does not check the .bin folder for executables, so if you use npm you will either have to change the scripts to explicitly run the firebase binary from node_modules/.bin/ or install firebase-tools globally and remove it from the devDeps list. Have a look at the Next.js repo's example for how I recommend using npm.

  • Ensure you're running Node 6.11.5 as the functions emulator requires this. I recommend asdf as a version manager and have add an asdf .tool-versions file to define the Node runtime.

  • If using _app.js you may receive the following error on your deployed Cloud Function:

    { Error: Cannot find module '@babel/runtime/regenerator'...
    

    Despite next.js having @babel/runtime as a dependency, you must install it as a dependency directly in this project.

Installation

git clone https://github.com/jthegedus/firebase-functions-next-example
cd firebase-functions-next-example
yarn install

Login to Firebase CLI

This is used as a dev-dependency instead of a global install. I've found this to be a much nicer dev experience.

yarn fblogin

Next.js Development

Standard Next.js development with Hot-module Reloading etc

yarn dev

Local Testing

yarn serve

This finally works now! Note: you must have a valid Firebase project id defined in the .firebaserc file as the serve command does check that the project exists. I believe this is to do with ensuring the relative routes align with your deployed application as the <project id> is used in your URLs.

For those who want to dig deeper into what's actually happening here run this command:

yarn serve --debug

Deploy to Firebase

You will need to connect the project to your Firebase project. Edit the name in .firebaserc or run firebase init and choose not to override any files.

Deploy Hosting resources and the rewrite Cloud Function

yarn deploy-app

Deploy functions not used for the SSR

Deploy all functions specified in the function group. Edit this script to add more function groups. - see Partial deploys docs for how to use function groups.

yarn deploy-funcs

Deploy everything to Firebase

yarn deploy-all

Clean dist Folder

yarn clean

A note on Code Compatibility

Everything was tested on Ubuntu 17.04 with Bash. This should work on Bash on Ubuntu on Windows without any changes. If you wish for Windows native support please submit an issue so we can work on Windows compatibility. Please report any macOS errors as I do not have access to a device to test. My development environment can be found here.

firebase-functions-next-example's People

Contributors

dependabot[bot] avatar jthegedus avatar teganlovesunicorns avatar tomvdv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-functions-next-example's Issues

how to user a custom HTML template for render

my client is using a template HTML page where i need to insert my nextjs application

this template is changing in real time, so i need to implement a render version of nextjs application with this template

which is the best way to do that?

yarn serve not work

hi,
when i run yarn serve and go in to the url http://localhost:5000 i receive this error:

info: User function triggered, starting execution
info: Execution took 2897 ms, finished with status: 'crash'
127.0.0.1 - - [07/Aug/2017:17:46:19 +0000] "GET / HTTP/1.1" 500 99 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
info: Execution took 65889 ms, finished with status: 'timeout'
Error: Can't set headers after they are sent.

Have you this error??

Incorporating Firebase Auth

Hey James! Thank you so much for your articles and code. It helped me get started with my website knophy.com. I've still got a lot of learning to do, but you really helped.

To the point: In this example (https://github.com/zeit/next.js/tree/canary/examples/with-firebase-authentication), Firebase Auth is baked into the request from the server using express.

I tried to set this up [1] (naively and ignorantly) within the Firebase cloud function, but it isn't working. Can you help me figure out or offer a better solution for saving the user in the request object so we can access it server side?

[1] https://github.com/technoplato/knophy/commit/67109aebf6c45d763ac31ee4f026e6384683cc96

Thanks in advance!

babel-runtime issues

Hey @jthegedus,

I tried to get fancy with some spread operators and firebase cloud functions was throwing Babel issues.

handleChange( event ) {
        this.setState({
            ...this.state,
            fields: {
                ...this.state.fields,
                [ event.target.name ]: event.target.value 
            }
        })
    }

Error thrown by Firebase functions:

{ Error: Cannot find module 'babel-runtime/helpers/defineProperty'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/user_code/next/dist/pages/donate/index.js:7:24)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3) code: 'MODULE_NOT_FOUND' }

I was able to fix by yarn add babel-runtime in src/app. I thought I got it working like with this command but no combination of adding babel runtime will allow me to compile locally and on firebase functions

inconsistent information

Hi!
impossible to enjoy by this example:

  1. firebase serve command fire hosting only. Maybe need firebase serve --only functions,hosting ?
  2. In Medium post says about necessity moving functions to src folder with appropriate firebase.json:
{
  "hosting": {
    "public": "src/public"
  },
  "functions": {
    "source": "src/functions"
  }
}

In your example functions/next folder created in dist folder:

{
  "hosting": {
    "public": "dist/public",
    "rewrites": [
      {
        "source": "**/**",
        "function": "next"
      }
    ]
  },
  "functions": {
    "source": "dist/functions"
  }
}
  1. process.env.NODE_ENV in functions does not defined at all

in this state, the example (with serve --only functions, hosting) on http://localhost:5000 return error:

function info: Execution took 3644 ms, finished with status: 'crash'
in browser:
{"error":{"code":500,"status":"INTERNAL","message":"function crashed","errors":["socket hang up"]}}
what is for
"build-functions": "babel \"src/functions\" --out-dir \"dist/functions\" --copy-files" ?

also takes place favicon problem

exports.next = functions.https.onRequest((req, res) => {
    console.log('File: ' + req.originalUrl);
// File: /favicon.ico

please give the correct working version, so that we're can try, how it works,
thanks

Can not deploy when dev = false

I got the following error when I set dev = false
in src/functions/index.js

-var dev = process.env.NODE_ENV !== "production"
+var dev = false

and try to deploy with yarn deploy
=== Deploying to 'nextjs-demo'...

i deploying functions, hosting
i functions: ensuring necessary APIs are enabled...
i runtimeconfig: ensuring necessary APIs are enabled...
โœ” runtimeconfig: all necessary APIs are enabled
โœ” functions: all necessary APIs are enabled
i functions: preparing dist/functions directory for uploading...

Error: There was an unknown problem while trying to parse function triggers. Please ensure you are using Node.js v6 or greater.
error Command failed with exit code 2.

the code deployed just fine when dev == true

I'm using macOS with
nvm 0.33.2
node 6.11.1
yarn 1.3.1

Unexpected identifier prepare() on function deploy

After trying to add my own functions and deploying them I get the following error:

Detailed stack trace: /user_code/node_modules/next/node_modules/next-server/dist/server/next-server.js:93
    async prepare() { }
          ^^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Module._compile (module.js:549:28)
    at Object.Module._extensions..js (module.js:586:10)
    at Module.load (module.js:494:32)
    at tryModuleLoad (module.js:453:12)
    at Function.Module._load (module.js:445:3)
    at Module.require (module.js:504:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/user_code/node_modules/next/node_modules/next-server/index.js:2:52)

This along with a typical "Unable to deploy functions error". I've made sure all dependencies are installed and I'm logged in and everything. Here's an excerpt from my yarn error log:

Arguments: 
  /usr/local/bin/node /usr/local/bin/yarn deploy-functions

PATH: 
  /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/go/bin:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/usr/local/git/bin

Yarn version: 
  1.5.1

Node version: 
  10.15.0

Platform: 
  darwin x64

This is happening on both my mac and windows (linux subsystem) environments

Cannot find module 'babel-runtime/regenerator'

Hi,

First I would like to thank you for this great contribution!

I used your project as a base to integrate a template which uses next and react and I got an error Cannot find module 'babel-runtime/regenerator', when the project has been deployed on firebase.

Your base project works fine on firebase, but the problem seems to be related to next/react. Here is my deps part of package.json, could you take a look ?

"dependencies": {
"antd": "^3.0.3",
"antd-local-icon": "^0.1.3",
"auth0-lock": "^11.7.2",
"babel-plugin-inline-import": "^3.0.0",
"card-react": "^1.2.7",
"chart.js": "^2.7.2",
"clone": "^2.1.1",
"cookie-parser": "^1.4.3",
"coolors-to-hex": "^1.0.3",
"firebase-admin": "^5.12.1",
"firebase-functions": "^1.0.4",
"frappe-charts": "^1.1.0",
"google-maps-react": "^2.0.2",
"immutable": "^3.8.2",
"inline-import": "^1.0.0",
"isomorphic-fetch": "^2.2.1",
"js-cookie": "^2.2.0",
"js-info-bubble": "git+https://github.com/RedQ/js-info-bubble.git",
"js-rich-marker": "^1.1.2",
"jwt-decode": "^2.2.0",
"leaflet": "^1.3.1",
"leaflet-routing-machine": "^3.2.8",
"leaflet.markercluster": "^1.3.0",
"lru-cache": "^4.1.3",
"next": "^6.0.3",
"next-redux-saga": "^3.0.0-beta.1",
"next-redux-wrapper": "^2.0.0-beta.6",
"nprogress": "^0.2.0",
"prop-types": "^15.6.1",
"react": "^16.4.0",
"react-addons-shallow-compare": "^15.6.2",
"react-big-calendar": "^0.19.1",
"react-chartjs-2": "^2.7.2",
"react-cookie": "^2.2.0",
"react-custom-scrollbars": "^4.2.1",
"react-dates": "^16.7.0",
"react-dnd": "^4.0.5",
"react-dnd-html5-backend": "^4.0.5",
"react-dom": "^16.4.0",
"react-drawer": "^1.3.4",
"react-dropzone-component": "^3.2.0",
"react-flip-move": "^3.0.2",
"react-ga": "^2.5.3",
"react-google-charts": "^1.6.6",
"react-helmet": "^5.2.0",
"react-instantsearch": "^5.1.0",
"react-intl": "^2.4.0",
"react-motion-drawer": "^3.1.0",
"react-placeholder": "^3.0.1",
"react-quill": "^1.2.7",
"react-redux": "^5.0.7",
"react-smooth-scrollbar": "^8.0.6",
"react-speech-recognition": "^1.0.6",
"react-tag-box": "^1.6.0",
"react-throttle": "^0.3.0",
"react-trend": "^1.2.4",
"react-vis": "^1.9.4",
"react-window-size-listener": "^1.2.1",
"react-youtube": "^7.6.0",
"recharts": "^1.0.0-beta.10",
"redux": "^4.0.0",
"redux-saga": "^0.16.0",
"redux-thunk": "^2.3.0",
"reselect": "^3.0.1",
"rheostat": "^2.2.0",
"smooth-scrollbar": "^8.3.0",
"styled-components": "^3.3.2",
"styled-theme": "^0.3.3",
"styled-tools": "^0.5.0",
"uppy": "^0.25.5",
"uuid": "^3.2.1"
},
"devDependencies": {
"@babel/cli": "^7.0.0-beta.42",
"@babel/core": "^7.0.0-beta.42",
"@babel/preset-env": "^7.0.0-beta.42",
"@firebase/app-types": "^0.3.2",
"cpx": "^1.5.0",
"firebase-tools": "^3.18.6",
"prettier": "^1.13.5",
"rimraf": "^2.6.2",
"babel-plugin-import": "^1.4.0",
"babel-plugin-styled-components": "^1.1.7",
"babel-plugin-transform-define": "^1.3.0",
"cross-env": "^5.0.5",
"webpack-bundle-analyzer": "^2.9.2",
"sass-loader": "^7.0.3",
"style-loader": "^0.21.0",
"node-sass": "^4.9.0",
"image-webpack-loader": "^4.3.1",
"css-loader": "^0.28.11",
"file-loader": "^1.1.11"
}

Thank you

Pierre

Cloud functions logs throws error cannot find module

"Cannot find module next\dist\server\document.js"
"Cannot find module next\dist\lib\error.js"

and throws in error 500 ... and I did not forget the trailing slash

maybe has to do with the version of Next? I'm not sure what "beta" version refers to

Edit: it works in development locally, just not on cloud functions

Add SCSS/SASS import

Hi! Very love your solution!

Can you add example which can explain how to import SCSS/SASS to .js or compile them to file (.css).

Thank you!

you need to await the app.prepare

your app sometimes can throw error 429 on firebase functions, because export server was more faster than app.prepare.. you need wait promise for export after.. I guess...

Image assets

Hello,

I tried adding images, but since this repo changes /static/ to /public/, it appears images break.

So,

  1. I renamed src/public/ to src/static all told yarn functions to use /static/ inside package.json
  2. I rebuilt
  3. Ran yarn run dev -> but images don't work
  4. Ran yarn run serve -> images do work, but you cannot have the /static/ path in them inside your image src in the page code. i.e.:

<img src="image.jpg" />
not
<img src="/static/image.jpg "/> from the next.js docs.

So, when I serve locally I can see the images. But this is only halfway working. It's hard to dev.

  1. Are others seeing what I'm seeing?
  2. Any way to have images working all the time?
  3. Any issue with changing back to /static instead of /public?

Native Windows support

Would like to help with this if possible. Dev is obviously running just fine, but serve, serve --debug, and deploy not so much. Have not attempted on Bash on Ubuntu on Windows. Changing package.json...
"serve": "NODE_ENV=production yarn firebase serve --only functions,hosting",
to "serve": "SET NODE_ENV=production yarn firebase serve --only functions,hosting",
and likewise in build runs just fine, but on serve doesn't seem to complete and on deploy returns a "can't communicate with function" error.

Integrate firebase realtime database example

Hi @jthegedus . This is not an issue but a question. Are you interested if I create a PR for adding an example page doing a firebase realtime database example?

I ask this because I've been several days working on this until I've found the way to do it properly. I dig on the web, and of course I had a learning curve that cost me that amount of time.

But in the end I think that it'd be nice for people to have both sides of firebase in the same example: cloud functions for the backend tasks and frontend functions for the realtime database API.

Basically, I took the way that is done at https://github.com/now-examples/next-news with minor modifications.

Let me know and I'll do the PR between today and tomorrow.

Regards and nice work, man. It helped me a lot

@google-cloud/functions-emulator | Suggested Solution

Hello,
I'm sorry if I'm writing in the wrong place but I have a suggested solution for @google-cloud/functions-emulator error and it's working with node 8 >= and I don't know where to write it except here.

For me, the solution was uninstalled firebase-tools from the project and install it globally using npm
npm install -g firebase-tools

after that I changed the script in package.json to be:
"serve": "NODE_ENV=production firebase serve --only functions,hosting",
"deploy-app": "firebase deploy --only hosting,functions:app",
"deploy-functions": "firebase deploy --only functions:greetings",
"deploy-all": "firebase deploy",

As you can check I delete yarn firebase and make it firebase only and it's working great!

I hope you found this solution good for you and good luck!

Cache-Control

Hi there,

I'm trying to cache the next.js response in the edges of the firebase cdn. Regarding to their tutorials it's as easy as adding res.set("Cache-Control", "public, max-age=600, s-max-age=1200"); which I did.
Do you know if there are any drawbacks? Don't want to run into them later on..

style jsx doesn't work on firebase but does on local dev server

When I add this code to my component

<style jsx>{`
  
  .header {
    flex: 0 0 50px;
    justify-content: center;
    align-items: center;
    display: flex;
  }

  .header__conteainer {
    
  }

  .header__link {
    margin: 0 20px;
  }

`}</style>

it works fine on yarn dev but when I do yarn deploy-app it deploys successfully and when I load page (on firebase) I see 500 error. And in console 500 - Internal Server Error. undefined

ubuntu 18 (pop os)
also I use nvm and node v6.11.5
steps to reproduce:

  1. clone the project
  2. past that code right above closing </header> in Header.js
  3. run yarn deploy-app

Anyone had any luck with firebase functions on node 8 and next 6.1

I tried deploying to firebase functions using {engines: { node: 8 } } and after several struggles I'm stuck at

{ Error: Cannot find module 'next/document'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.21 (/srv/next/server/bundles/pages/_document.js:223:18)
    at __webpack_require__ (/srv/next/server/bundles/pages/_document.js:23:31)
    at Object.20 (/srv/next/server/bundles/pages/_document.js:107:72)
    at __webpack_require__ (/srv/next/server/bundles/pages/_document.js:23:31)
    at Object.19 (/srv/next/server/bundles/pages/_document.js:92:18)
    at __webpack_require__ (/srv/next/server/bundles/pages/_document.js:23:31) code: 'MODULE_NOT_FOUND' }

I also have Error: Cannot find module 'next/error' but I figure that's the same thing

Working with service worker offline

Have raised an issue at

Issue Link

firebase-functions-next-example is the starter I have used .

Can you please help . Just starting out with Next js and trying to make it offline using firebase functions .

Thanks

'NODE_ENV' is not recognized as an internal or external command

When i run "yarn serve" command in windows, it throws an error like below:

yarn run v1.2.0
$ yarn build-public && yarn build-funcs && yarn build-app && yarn copy-deps && yarn install-deps
Successfully compiled 4 files with Babel.
'NODE_ENV' is not recognized as an internal or external command,
operable program or batch file.
error Command failed with exit code 1.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.