NextJS with Google Cloud Functions in 10 minutes.

We can go full serverless with Google Cloud functions + NextJS including handling all our static files in just 10 minutes!

I’m assuming

  • You know NextJS
  • You know Express and NodeJS
  • You know Google Cloud functions

I will guide you to the basic steps to ensure your nextjs go full serverless. Lets get started with installing the dependencies after you did npm init

Install Dependencies and set up NextJS Serverless

npm install react react-dom express next --save

create index.js in /src/pages/ directory and write a simple component

import React from ‘react’export default () => {
return (<p>I’ve just went serverless with NextJS and google cloud functions</p>)
}

ensure the following are inside your package.json

“scripts”: {
“dev”: “next dev”,
“build”: “next build”,
“start”: “next start”
},

Next up, go to your terminal and type npm run dev and you should see the following. Now your NextJS application is running!

The easiest way to set up NextJS on Google Cloud Functions, and go Serverless, is to set up an Express server as a entry point for functions.

Through the Express Server, all your routing will be managed by it instead of creating hundreds of functions to run your web app.

If you haven’t set up custom server for NextJS before, don’t worry, just create server.js in your root folder and copy/paste these codes below.

const next = require(‘next’)
const app = next({ dev: false })
const handle = app.getRequestHandler()
const slasher = handler => (req, res) => {
if (req.url === ‘’) {
req.url = ‘/’
}
return handler(req, res)
}
module.exports.handler = slasher((req, res) => {
return app.prepare()
.then(() => handle(req, res))
.catch(ex => {
console.error(ex.stack)
process.exit(1)
})
})

Next up, create next.config.js in your root folder with the following lines. These few lines ensure we create a .next build folder with all the necessary files, and add prefixes to all our static files.

const isProd = process.env.NODE_ENV === ‘production’
module.exports = {
target: ‘serverless’,
assetPrefix: isProd ? ‘https://we.will.fill.this.up.later' : ‘’,
}

Note: the assetPrefix should be in the follow form, but if you don’t know the URL, it’s fine, we will get the exact URL later and save your trouble.

https://<region>-<project-id>.cloudfunctions.net/<function-name>

Now we are all ready to set up google cloud functions!

Install gcloud and initialize project. If you haven’t already have a gcloud you need to follow https://cloud.google.com/sdk/docs/initializing to set up your gcloud console and initialize it. It’s very easy. Just a couple of steps in your terminal. After you have install gcloud, just type gcloud init and follow the instructions in the terminal to create project-id and config your project-id.

Once you have set it up, we are good to go. Now open up your package.json and make sure your script tags are as follows

“scripts”: {
“dev”: “node server.js”,
“build”: “next build”,
“deploy”: “gcloud functions deploy nextjs --entry-point=handler --allow-unauthenticated --trigger-http --runtime=nodejs10 --memory=128MB”,
},

What we are doing here is deploying a function named nextjs calling the handler function we created in server.js. We also add options so it can be accessed by anyone who knows the end point (trigger-http), running on nodejs10 with 128MB memory allocated each time the function runs.

2nd Last Step — WOW we are moving so fast to deploying our NextJS on google cloud functions!

npm run build
npm run deploy

Once you proceed with deploy, it will ask you whether to enable the API, just reply ‘y’ to proceed with retry and deploy and you will see the following in a couple of minutes.

go to the url in your browser and you will see your page deployed successfully!

But wait, when you inspect the page, you will see a bunch of reds, indicating that the static files are not loading.

Now, do you remember we were creating next.config.js and I told you we need to enter some URL?

Go back to your next.config.js and enter the url provided by your gcloud deploy

const isProd = process.env.NODE_ENV === ‘production’module.exports = {
target: ‘serverless’,
assetPrefix: isProd ? ‘https://enter.the.full.url.return.by.your.gcloud.deploy' : ‘’,
}

now go back to your terminal and build + deploy with your new next.config.js once more

npm run build
npm run deploy

There we go, the files are loaded from the correct place.

Works for your API path too.

So there we go, setting up our NextJS and going serverless with Google Cloud Functions in under 10 minutes.

Leave me a comment if you want me to write more on serverless functions.

--

--

--

entrepreneur, developer, dream chaser

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Application Insights using Azure and VueJs — Error handling and Event Logging in Front End to…

JWT Authentication using C#

Controlling Arduino with JavaScript

Greyscale picture of computer with code inside

Nuxtjs + Lottie

What is Hoisting in JavaScript?

Contux — Flux like State Management using enhanced components on top of the new React Context API

A Byte of Coding Issue #217

Livewire — An Easy Way To Build Dynamic Web Applications (Part 1)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dave Teu

Dave Teu

entrepreneur, developer, dream chaser

More from Medium

April Releases: customizable webhook payloads, custom prices in checkout, and more!

No-code platforms: When should you switch to a custom-built solution?

How to connect Supabase and Nextjs

A Web Framework To Help You With Search Engine Optimization (SEO)