Logo
Published on

How to Deploy a TypeScript NestJS Cloud Function on the Google Cloud Platform

Authors
  • Name
    Twitter

Are you eager to deploy your TypeScript-based NestJS cloud function on the Google Cloud Platform (GCP)? This guide will lead you through the step-by-step process to get your cloud function up and running on GCP.

Step 1: Create Your Cloud Function

Before we embark on deployment, let’s start by creating your cloud function. We’ll use an example to help us illustrate the process:

import {  
  Request,  
  Response,  
  cloudEvent,  
  http,  
} from '@google-cloud/functions-framework';  
  
function runGenericCloudFunction() {  
   cloudEvent(functionName, async (event: any) => {  
      try{  
             // Your logic here  
      }catch(error) {  
         logger.error(error.toString(), error.stack);  
         throw error;  
       }  
   });  
}

Step 2: Organize Your Project Structure

A well-organized project structure is crucial for a seamless deployment. Ensure that your package.json file resides at the root level of your project directory. GCP will attempt to run the build command on your project, compiling it and generating the dist folder containing the compiled JavaScript code.

.  
├── node_modules  
├── package-lock.json  
├── package.json  
└── src  
 └── main.ts

Remember that you’ll run the command line at the level of package.json, and you should include this command in your package.json:

"main": "dist/main.js"

This command specifies the location of the main function in .js after being compiled for GCP.

Step 3: Authenticate with Google

To deploy your function successfully, you’ll need to authenticate with Google using the Google Cloud CLI. Make sure you’re logged in with the appropriate Google account in your terminal.

Step 4: Deploy Your Application

Finally, use the following command to upload your application on the Google Cloud Platform:

gcloud functions deploy FUNCTION_NAME \  
 - gen2 \  
 - runtime=nodejs18 \  
 - set-env-vars [ADDITIONAL_VARS] \  
 - entry-point=ENTRY_FUNCTION \  
 - memory=MEMORY_TO_YOUR_APPLICATION \  
 - project=PROJECT \  
 - region=REGION \  
 - source=. \  
 - trigger-topic=PUBSUB_TOPIC_NAME

By following these steps above, you can ensure your function will be successfully deployed on Google Cloud Platform.

Reach out to me on LinkedIn. Let’s connect: https://www.linkedin.com/in/matheus-araujo-souza/

My GitHub:

MatheusAraujoSouza

My Instagram:

https://www.instagram.com/mhatheusss_/