Deploying the NodeJS TypeScript Function to Google Cloud Function
Introduction
Google Cloud Functions (GCF) is a component of Google Cloud Platform (GCP) that allows you to deploy functions in a simple and flexible way. With a serverless approach, you can focus on developing your product without spending much time and effort managing infrastructure or cloud storage.
I previously wrote about deploying a NodeJS TypeScript application to Google App Engine. Now, let's explore how Google Cloud Functions can help you deploy the necessary functions on-demand. GCF supports multiple runtime environments such as NodeJS, Golang, Python, Ruby, Java, and .NET.
You can create a Cloud Function directly through the Google Cloud Console or via the Google Cloud CLI. In this article, I'll guide you through using the Google Cloud CLI to deploy a Cloud Function developed with NodeJS and TypeScript.
Prerequisites
Before we proceed, make sure you have the following:
- A Google Cloud account with Cloud Functions enabled
- Basic knowledge of NodeJS. You can refer to this guide to set up a NodeJS TypeScript project used in this article.
Implementing the Cloud Function
Once you've set up your NodeJS TypeScript project, install the following package:
Then, change the content of the `main.ts` file as follows.
You can see that implementing functions with the functions-framework is quite straightforward, similar to using express. I've also defined both GET and POST methods as examples.
Next, add the following line to define the build file for the cloud function in the package.json file:
Note that the "dist" directory is the output folder after building the project into JavaScript. Cloud Functions support JavaScript by default, so for this project, which is implemented in TypeScript, you need to specify the JavaScript file after the build.
To start the project in development mode, follow these steps:
- --target: This is the function name you want to deploy.
- --source: Specify the directory of the JavaScript file after building.
Here’s the result:
To deploy the Cloud Function, do the following:
- --runtime: Use the command `gcloud functions runtimes list` to see the list of runtimes supported by Cloud Functions.
- --region: Optional, replace with your region.
- --allow-unauthenticated: This makes your function public. Without this, authentication is required to use the function.
After a successful deployment, a URL will be generated for using the Cloud Function. The URL will look like this: `https://{region}-{project-id}.cloudfunctions.net/{cloud-function-name}`.
The result is as follows:
See you in the next articles!
Comments
Post a Comment