Firebase

How to set up Firebase Hosting with Next.js for server-side rendering?

Discover a step-by-step guide on setting up Firebase Hosting with Next.js to enable server-side rendering. Enhance your web app's speed and efficiency effortlessly.

Developer profile skeleton
a developer thinking

Overview

This question is all about combining Firebase Hosting with Next.js to make server-side rendering happen. This combo can really boost SEO and make pages load super fast. To get it up and running, you'll need several pieces. First, jump into creating a Firebase project. Then, you should set up Firebase Hosting. Configuring a Next.js project comes next. Finally, deploy your app to Firebase.

You will use some JavaScript, understand server-side rendering, and have a basic grasp of Firebase & Next.js. The magic happens when you merge Firebase's scalable hosting with Next.js's server-side rendering capabilities. A key part of this is writing and deploying cloud functions to serve your Next.js app via Firebase. If all steps are done right, your app's performance will soar.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to set up Firebase Hosting with Next.js for server-side rendering?

Step 1: Pre-requisites

Alright, let's get everything ready before we dive in. Here's what you'll need:

  • Node.js and npm: These are essential for running the development version of your Next.js app and installing dependencies.
  • Google Firebase CLI: Install it using npm with this command: npm install -g firebase-tools.
  • A Firebase project: Sign up or log in to Firebase and create a new project in the Firebase console.

Step 2: Create a Next.js App

First things first, let's create a new Next.js application. Open your terminal and run npx create-next-app@latest. Follow the prompts to set up your new app.

Step 3: Initialize Firebase Project

Once your Next.js app is ready, navigate into its directory with cd your-project-directory. Then, initialize your Firebase project by running firebase init. When prompted, select Functions and Hosting. Choose the Firebase project you created earlier. Pick JavaScript as your language, and say 'yes' to using ESLint.

For the hosting configuration:

  • Public directory: Type “build”
  • Single-page app: Answer “No”
  • Auto build and deploy before each deploy: Answer “No”

This will create a functions directory and some configuration files.

Step 4: Set up Firebase Function for Server-Side Rendering

To enable server-side rendering, you'll need to set up a Firebase function. Write the following code inside functions/index.js, which was generated during the Firebase initialization:

const functions = require('firebase-functions');
const next = require('next');

var dev = process.env.NODE_ENV !== 'production';
var app = next({ dev, conf: { distDir: 'next' } });
var handle = app.getRequestHandler();

exports.nextApp = functions.https.onRequest((req, res) => {
  console.log('Fetch UserAgent from Cloud Function:', req.headers['user-agent']);
  return app.prepare().then(() => handle(req, res));
});

Here, app.prepare() handles the server-side rendering, while handle(req, res) processes the request and sends the server-rendered page to the browser.

Step 5: Update Firebase.json for Rewrites

Next, update your firebase.json file to redirect all hosting requests to the Firebase function you just set up. Add the "rewrites" section to the "hosting" part of firebase.json:

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
     ],
     "rewrites": [
       {
         "source": "**",
         "function": "nextApp"
       }
     ]
  },

Step 6: Build and Deploy

Now it's time to build your Next.js app and deploy it to Firebase. First, navigate to your Next.js app directory and run:

npm run build

The build output will be in the .next folder. Copy the contents of that folder into the functions/next folder by running:

cp -r .next/* functions/next/

Finally, deploy your app using the Firebase CLI with:

firebase deploy

And there you go! Your Next.js app with server-side rendering is now live on Firebase.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.