Next JS is a powerful framework for production based on react js. When it’s come to deployment most of the young developers were looking for free deployment with all features enabled. There we have few options. The one firebase powered by Google.
In this section we are going to deploy next is application in firebase for free. we can deploy next js project in fire base in two ways what is static way and the second one is dynamic using cloud functions. In deploying Static method using next export. some of the features were not working like Image Optimization (default loader), Internationalized Routing , API Routes, Incremental Static Regeneration, fallback: true, getServerSideProps
Now we are going to deploy the next js project with dynamic using cloud function and it will work all the features including
- Image Optimization (default loader)
- Internationalized Routing
- API Routes
- Rewrites
- Redirects
- Headers
- Middleware
- Incremental Static Regeneration
- fallback: true
- getServerSideProps
First, you have a firebase account and make sure you must upgrade to blaze plan. Why because of we need cloud functions without upgrading to blaze plan we can’t use cloud functions in firebase. firebase will provide 2,000,000 function invocations absolutely free of cost.
- Now Open your next JS project file directory and install the firebase CLI tools.
- · Login your firebase account using firebase login
- · Run the command firebase init hosting
- · Choose project or create new project
- · Select Default Public folder as public
- · Rewrite all URLs to Single page select Yes.
- · Delete index.html file in public folder. Otherwise, next js routing won’t work.
In your Root folder you will see a firebase.json file. Now we are going to edit like this below.
{
"hosting": {
"public": "public",
"site": "Your site name",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"function": "nextServer"
}
]
},
"functions": {
"source": ".",
"runtime": "nodejs18"
}
}
Create server.js file in your root directory and paste the below code.
const { https } = require('firebase-functions');
const { default: next } = require('next');
const isDev = process.env.NODE_ENV !== 'production';
const server = next({
dev:isDev,
conf: { distDir:'.next' },
});
const nextjsHandle = server.getRequestHandler();
exports.nextServer = https.onRequest((req, res) => {
return server.prepare()
.then(() => {
return nextjsHandle(req, res)
});
});
After configuring like above. Now change your run scripts in package.json like this.
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"deploy": "firebase deploy --only functions,hosting"
},
After this run npm run build, now you will see .next folder in your project root directory.
And finally, run the command deploy. And boom your will be deployed.