
Deploying a Next.js App on Firebase
Once you've built your amazing Next.js application, the next step is to deploy it to the world. Firebase Hosting is an excellent choice for deploying Next.js apps, offering a global CDN, easy setup, and seamless integration with other Firebase services. This guide will walk you through the process.
Prerequisites
- A Next.js project ready for deployment.
- A Firebase account. If you don't have one, you can create one for free.
- Node.js and npm installed on your machine.
Step 1: Install Firebase CLI
First, you need to install the Firebase Command Line Interface (CLI) globally on your machine. Open your terminal and run:
npm install -g firebase-tools
Step 2: Login to Firebase
After installing the CLI, you need to log in to your Firebase account:
firebase login
This will open a browser window for you to authenticate with your Google account.
Step 3: Initialize Firebase in Your Project
Navigate to your Next.js project's root directory in the terminal and run:
firebase init hosting
The CLI will ask you a series of questions:
- Please select an option: Choose "Use an existing project" and select the Firebase project you want to use.
- What do you want to use as your public directory? Enter
.next
. Next.js builds the production app into the.next
directory. - Configure as a single-page app (rewrite all urls to /index.html)? Enter
No
. Next.js handles its own routing. - Set up automatic builds and deploys with GitHub? Choose
No
for now. You can set this up later.
This will create two files in your project: .firebaserc
and firebase.json
.
Step 4: Configure Rewrites for Server-Side Rendering
For Next.js features like SSR and API routes to work, you need to tell Firebase Hosting to forward requests to a server-side function. Open your firebase.json
file and add a rewrites
section inside the hosting
configuration:
{
"hosting": {
"public": ".next",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "server"
}
]
}
}
You also need to tell Firebase where your Cloud Function code is located. Add a functions
section to firebase.json
:
{
"functions": { "source": ".", "runtime": "nodejs18" },
"hosting": { ... }
}
Step 5: Build and Deploy
First, build your Next.js app for production:
npm run build
Then, deploy your app to Firebase Hosting:
firebase deploy
After the deployment is complete, the CLI will give you a URL where you can view your live application. That's it! Your Next.js app is now live on Firebase.