loading...

How to add Basic Auth in Next.js apps with Firebase Hosting and SSR

ut0n69 profile image ut0n ・2 min read

Overview

Next.js has no method for Basic Auth. So we gonna use Express.js.
Also I'll use template: with-firebase-hosting-and-typescript.

Require:

  • Node.js v10.x.x
  • firebase-tools@latest

Steps

Set up Next.js app

We check this README.

# bash

yarn create next-app --example with-firebase-hosting-and-typescript with-firebase-hosting-and-typescript-app

Install modules

  • express
  • @types/express
  • next-routes
  • basic-auth-connect
# bash

yarn add express next-routes basic-auth-connect

bash

# bash

yarn add -D @types/express

Error handling

(If you get this error)

Error: > Couldn't find a `pages` directory. Please create one under the project root

We gonna fix functions, because this template can't deploy firebase functions. (Apr 1st.2020)

// src/functions/index.ts

const app = next({ dev, conf: { distDir: 'next' } })


// src/functions/index.ts

const app = next({ dev: false, conf: { distDir: 'next' } })

Develop

// src/functions/index.ts

import * as functions from 'firebase-functions';
import next from 'next';
import express from 'express';

/* eslint-disable @typescript-eslint/no-var-requires */
const routes = require('next-routes');
const basicAuth = require('basic-auth-connect');

const USERNAME = 'user';
const PASSWORD = 'password';

const server = express();

const app = next({ dev: false, conf: { distDir: 'next' } });
const handler = routes().getRequestHandler(app);
server.use(basicAuth(USERNAME, PASSWORD));
server.get('*', (req, res) => handler(req, res));

export const nextApp = functions.https.onRequest(server);

Set up Firebase Project

We gonna change this: <project-name-here> to our firebase project name.

# .firebaserc

{
  "projects": {
    "default": "<project-name-here>"
  }
}

Run

At local

We gonna use firebase-emulators for testing on local.

Build

yarn preserve

Run

firebase emulators:start

Deploy

firebase deploy

Have fun ☺️
Thanks.

Discussion

pic
Editor guide
Collapse
tonoli profile image
Ignacio Tonoli

Error: > Couldn't find a 'pages' directory. Please create one under the project root

This error comes from the fact that you don't have a env variable to set to production. There is a way to set environment variables in firabase: firebase.google.com/docs/functions...