Deploying Next.js app on Firebase Hosting requires few step to get your app up and running. Nx provides you a comprehensive build system to structure your multiple apps into a single repository. In the tutorial we are going to see how to deploy a Next.js app as a Static Site Generation(SSG) using Firebase Hosting. Let’s start by setting up Nx workspace and adding our Next.js app.
Setting up Nx workspace and adding Next.js app
Here are the steps to initialize a new nx workspace and add our Next.js app
- Initialize a new Nx workspace:
- First, install the Nx CLI globally by running
npm install -g nx. - Then, create a new Nx workspace by running
npx create-nx-workspace@latest. - Setup the repo using your preferences although the default once would do you just enough to get started.
2. Create a new Next.js application:
- In your Nx workspace, create a new Next.js application by running
nx g @nrwl/next:application next-app.
Once your done generating the app goto next.config.js file add the output:export option to the nextConfig object
//@ts-check
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { composePlugins, withNx } = require('@nx/next');
const path = require('path');
/**
* @type {import('@nx/next/plugins/with-nx').WithNxOptions}
**/
const nextConfig = {
output: 'export', // add this line
nx: {
// Set this to true if you would like to use SVGR
// See: https://github.com/gregberge/svgr
svgr: false,
},
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.resolve.alias['@'] = path.join(__dirname, 'src');
return config;
},
};
const plugins = [
// Add more Next.js plugins to this list if needed.
withNx,
];
module.exports = composePlugins(...plugins)(nextConfig);
The outout directory is the default distDir used by Next.js to export your app to a statically generated file.
Setting up Firebase project
Firebase is an excellent choice for prototyping web applications due to its comprehensive suite of development tools and services. It offers a real-time database, user authentication, cloud storage, hosting, and much more out of the box. This allows developers to rapidly build and prototype applications without having to manage infrastructure or write server-side code.
Firebase’s support for CI/CD through tools like GitLab CI/CD makes it possible to automate the deployment process, thus further speeding up the development cycle and ensuring that your application is always up-to-date with the latest features and improvements.
- Create a new Firebase project:
- Go to the Firebase Console.
- Click on “Add project”.
- Follow the prompts to add a new project.
2. Install Firebase tools:
- Install the Firebase CLI globally by running
npm install -g firebase-tools. - Login to Firebase CLI by running
firebase login:ciThis will help you to choose your firebase projects from the terminal.
3. Initialize Firebase in your Next.js application:
- Navigate to the next-app directory where you generated you Next.
- Run
firebase init. - Choose “Hosting” when prompted for which Firebase features you want to set up.
- Choose your Firebase project, continue with the options you want ot sent and finally choose “out” as your public directory.
Make sure you have your build directory defined in next.config.mjs matches the ones defined on firebase.json. If you have not defined any distDir in next.config.mjs, “out” will be your default directory
Your firebase.json file should like something similar to this
{
"comment": "add this after your exiting configs like firestore or functions",
"hosting": {
"public": "out",
"ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
"frameworksBackend": {
"region": "us-centeral1"
}
},
}
Setting up Gitlab CI/CD
Now, whenever you push changes to the master branch of your GitLab project, GitLab CI/CD will automatically build and deploy your Next.js application to Firebase.
To add CI/CD to your next app. We need to create a .gitlab-ci.yml file at the root of our nx application. Once you create the file, define the stages for linting, building and deploying. In the example below we have three environments, dev, uat and prod.
You can copy and paste this as a sample and adjust stage as your app needs.
image: node:latest
stages:
- lint
- build
- deploy
lint:
stage: lint
script:
- echo "Linting the next-app"
- npm install
- npm run lint
build:
stage: build
script:
- echo "Building next-app"
- npx nx build next-app --verbose
before_script:
- echo $GOOGLE_APPLICATION_CREDENTIALS > /tmp/key.json
- export GOOGLE_APPLICATION_CREDENTIALS=/tmp/key.json
deploy_dev:
stage: deploy
environment:
- dev #fetchs env vars for dev only
only:
- dev
script:
- npx firebase deploy --debug # you can remove `--debug`
deploy_release:
stage: deploy
environment:
- release #fetchs env vars for release
only:
- release
script:
- npx firebase deploy
deploy_prod:
stage: deploy
environment:
- main #fetchs env vars for prod
only:
- release
script:
- npx firebase deploy
Make sure that GOOLGE_APPLIATION_CREDENTIALS is readable by the CI job when you pass in the key file to tmp/key.json
Since Firebase has deprecated using --token to allow authentication of external services like GitLab CI, we need to apply the new approach for authentication. Google recommends to use a service account key with GOOGLE_APPLICATION_CREDENTIALS. To get this key you need to generate a service account key from the Google Cloud Console and then set it as an environment variable in your GitLab CI/CD pipeline. Here’s how you can do it:
- To generate a service account key:
- Go to the Google Cloud Console.
- Select your project.
- Go to IAM & Admin > Service Accounts.
- Click on “Create Service Account”.
- Fill in the details and click “Create”.
- Grant this service account an appropriate role. For Firebase, the “Firebase Admin” role should be sufficient.
- Click “Done” to create the service account.
- Click on the row of the service account that you just created.
- Click on “Add Key” and then “Create new key”.
- Select “JSON” and click “Create”. This will download a JSON file with your service account key.
2. Set the service account key as an environment variable:
- Open the downloaded JSON file and copy its contents.
- Go to your GitLab project.
- Go to Settings > CI/CD > Variables.
- Click on “Add Variable”.
- Set the key to
GOOGLE_APPLICATION_CREDENTIALSand the value to the contents of the JSON file (The key file you downloaded in the above step). - Click “Add Variable” to save it.
Once you save the GOOGLE_APPLICATION_CREDENTIALS you can now push changes to one of your defined branches and Gitlab CI will automatically tirgger the job to build and deploy your application.
I hope this guide will help you to deploy your apps within the Nx using Firebase Hosting and Gitlab CI. Feel free to give it your thoughts or suggestion. If you find it useful save and share it for others. Connect with me to get more related content on web development.
