Skip to content

Latest commit

 

History

History
51 lines (35 loc) · 2.62 KB

File metadata and controls

51 lines (35 loc) · 2.62 KB

Example: Firebase authentication with a serverless API

How to use

Using create-next-app

Execute create-next-app with Yarn or npx to bootstrap the example:

npx create-next-app --example with-firebase-authentication-serverless with-firebase-authentication-serverless-app
# or
yarn create next-app --example with-firebase-authentication-serverless with-firebase-authentication-serverless-app

Download manually

Download the example:

curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-firebase-authentication-serverless
cd with-firebase-authentication-serverless

Set up Firebase:

  • Create a project at the Firebase console.
  • Get your account credentials from the Firebase console at Project settings > Service accounts, where you can click on Generate new private key and download the credentials as a json file. It will contain keys such as project_id, client_email and client_id. Set them as environment variables in the .env file at the root of this project.
  • Get your authentication credentials from the Firebase console under Project settings > General> Your apps Add a new web app if you don't already have one. Under Firebase SDK snippet choose Config to get the configuration as JSON. It will include keys like apiKey, authDomain and databaseUrl. Set the appropriate environment variables in the .env file at the root of this project.
  • Set the environment variables SESSION_SECRET_CURRENT and SESSION_SECRET_PREVIOUS in the .env file. (These are used by cookie-session.]

Install it and run:

npm install
npm run dev
# or
yarn
yarn dev

Deploy it to the cloud with now (download)

now

After now successfully deploys, a URL will for your site will be displayed. Copy that URL and navigate to your Firebase project's Authentication tab. Scroll down in the page to "Authorized domains" and add that URL to the list.

The idea behind the example

This example includes Firebase authentication and serverless API routes. On login, the app calls /api/login, which stores the user's info (their decoded Firebase token) in a cookie so that it's available server-side in getInitialProps. On logout, the app calls /api/logout to destroy the cookie.