DEV Community

ut0n
ut0n

Posted on

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

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
Enter fullscreen mode Exit fullscreen mode

Install modules

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

yarn add express next-routes basic-auth-connect
Enter fullscreen mode Exit fullscreen mode

bash

# bash

yarn add -D @types/express
Enter fullscreen mode Exit fullscreen mode

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' } })
Enter fullscreen mode Exit fullscreen mode

↓

// src/functions/index.ts

const app = next({ dev: false, conf: { distDir: 'next' } })
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Set up Firebase Project

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

# .firebaserc

{
  "projects": {
    "default": "<project-name-here>"
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
tonoli profile image
Ignacio Tonoli • Edited

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...