In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
Today, I will talk to you about how to deploy an Serverless Next.js application elegantly. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something from this article.
How to quickly deploy Serverless Next.js
As I am familiar with Serverless Framework development tools and have been involved in related open source work for a long time, this article uses Serverless Components scheme for deployment. Please ensure that the current development environment has been globally installed with serverless command line tools before you start reading this article. This article still uses the Next.js components described in the previous article to help quickly deploy Next.js applications to Tencent Cloud Serverless services.
Let's quickly initialize a Serverless Next.js project:
$serverless create-u https://github.com/serverless-components/tencent-nextjs/tree/master/example-p serverless-nextjs$ cd serverless-nextjs
The project template has been configured with serverless.yml by default, and you can directly execute deployment commands:
$serverless deploy
The deployment will be successful in about 30 seconds, and then you can see the home page by visiting the generated apigw.url link https://service-xxx-xxx.gz.apigw.tencentcs.com/release/.
The Next.js component helps us create a cloud function and an API gateway by default, and associate them. In fact, we access the API gateway, and then trigger the cloud function to obtain the request return result. The flow chart is as follows:
Explanation: when we execute the deployment command, because a simple Next.js application not only includes business code, but also includes a large node_modules folder, which results in a packaged code volume of about 20m, so most of the time is spent on code upload. The speed here is also related to the network environment of the development environment, but in fact, our cloud deployment is very fast, which is why it takes about 30 seconds to deploy, and when the network is poor, it will take longer. Of course, we will also talk about how to improve the deployment speed later.
I'm sure you've realized that with the convenience of the Serverless Components solution, it can really help our applications deploy to the cloud efficiently. And the Next.js component used here also does a lot of optimization work for code upload to ensure rapid deployment efficiency.
Next, we will show you how to further optimize our deployment experience based on Next.js components.
How to customize the API Gateway Domain name
Partners who have used the API gateway should know that it can configure custom domain names, as shown in the following figure:
However, this manual configuration is still not convenient enough, so the Next.js component also provides customDomains to help developers quickly configure custom domain names, so we can add the following configuration to the serverless.yml of the project:
Org: orgDemoapp: appDemostage: devcomponent: nextjsname: nextjsDemoinputs: src: dist:. / hook: npm run build exclude:-.env region: ap-guangzhou runtime: protocols:-https environment: release enableCORS: true # Custom Domain name related configuration customDomains:-domain: test.yuga.chat certificateId: abcdefg # Certificate ID # here the API gateway's The release environment maps to the root path pathMappingSet:-path: / environment: release protocols:-https
Since the https protocol is used here, you need to configure the certificate ID hosted on Tencent Cloud service, which can be viewed in the SSL Certificate console. Tencent Cloud already provides the ability to apply for a free certificate. Of course, you can also upload your own certificate for hosting.
Then we execute the deployment command again and get the following output:
Since the domain name is mapped to the API gateway service through CNAME when customizing the domain name, you also need to manually add the CNAME resolution record in the red box of the output result. Wait for the custom domain name to be resolved successfully, then you can access it normally.
How to host static resources through COS
Next.js application, there are two static resources:
The project is used through the introduction of resources, which are packaged by Webpack and output to a .next / static directory, such as a .Next / static/css style file directory.
Put it directly into the public folder of the root directory of the project, return it through the static file service, and then the project can be introduced directly through url (official introduction).
The first kind of resource is easy to handle, and the Next.js framework directly supports configuring assetPrefix in next.config.js to help us add the access url that provides static resource hosting service to the static resource introduction prefix when building the project. As follows:
/ / next.config.jsconst isProd = process.env.NODE_ENV = = "production"; const STATIC_URL = "https://serverless-nextjs-xxx.cos.ap-guangzhou.myqcloud.com";module.exports = {assetPrefix: isProd? STATIC_URL: "",}
The STATIC_URL in the above configuration is the access url provided by the static resource hosting service. In the example, it is the corresponding COS access url of Tencent Cloud.
So how do we deal with the second resource? This is where the business code needs to be slightly modified.
First, you need to add the env.STATIC_URL environment variable to next.config.js:
Const isProd = process.env.NODE_ENV = = "production"; const STATIC_URL = "https://serverless-nextjs-xxx.cos.ap-guangzhou.myqcloud.com";module.exports = {env: {/ / 3000 is the port for local development, which is used to run STATIC_URL: isProd? STATIC_URL: "http://localhost:3000",}, assetPrefix: isProd? STATIC_URL: "",}
Then, modify the path to introduce static resources into public in the project, such as:
Create Next App Create Next App
Finally, add static resource-related configuration staticConf to serverless.yml, as follows:
Org: orgDemoapp: appDemostage: devcomponent: nextjsname: nextjsDemoinputs: src: dist:. / hook: npm run build exclude:-.env region: ap-guangzhou runtime: Nodejs10.15 apigatewayConf: # omitted here. # static resource-related configuration staticConf: cosConf: # here is the created COS bucket name bucket: serverless-nextjs
The COS bucket is specified by configuring staticConf.cosConf, and the static resources generated by compilation. next and public folders are automatically uploaded to the specified COS by default when the deployment is executed.
After modifying the configuration, execute serverless deploy again to deploy:
Serverless deployserverless ⚡ frameworkAction: "deploy"-Stage: "dev"-App: "appDemo"-Instance: "nextjsDemo" region: ap-guangzhou# is omitted here .staticConf: cos: region: ap-guangzhou cosOrigin: serverless-nextjs-xxx.cos.ap-guangzhou.myqcloud.com bucket: serverless-nextjs-xxx
When you visit the browser and open the debugging console, you can see that the static resource request path for access is as follows:
As can be seen in the figure above, static resources are obtained by accessing COS. Now cloud functions only need to render entry files, instead of returning static resources through cloud functions as before.
Note: since .Next was previously deployed to the cloud function, after the page cannot be accessed, the static resources on the page, such as images, need to access the cloud function again and then obtain it. Therefore, it seems that we have requested a cloud function, but in fact, the number of concurrency per unit time of cloud function will increase according to the number of static resource requests on the page, resulting in cold start problem.
Static resource configuration CDN
Above, we have deployed all the static resources to COS, and the page access is much faster. But for production environments, you also need to configure CDN for static resources. The CDN accelerated domain name can be easily configured through the COS console. But it still needs to be configured manually, and as a lazy programmer, I still can't accept it. The Next.js component just provides the ability to configure CDN for static resources. You only need to add staticConf.cdnConf configuration to serverless.yml, as shown below:
# omitted here. Inputs: # omitted here. # static resource-related configuration staticConf: cosConf: # here is the created COS bucket name bucket: serverless-nextjs cdnConf: domain: static.test.yuga.chat https: certId: abcdefg
The https protocol is used here, so the certId certificate ID configuration for https is also added. In addition, the static resource domain name needs to be modified to CDN domain name. Modify the next.config.js as follows:
Const isProd = process.env.NODE_ENV = = "production"; const STATIC_URL = "https://static.test.yuga.chat";module.exports = {env: {STATIC_URL: isProd? STATIC_URL: "http://localhost:3000",}, assetPrefix: isProd? STATIC_URL: "",}
Once configured, execute the deployment again, and the result is as follows:
$serverless deployserverless ⚡ frameworkAction: "deploy"-Stage: "dev"-App: "appDemo"-Instance: "nextjsDemo" region: ap-guangzhouapigw: # ellipsis... scf: # ellipsis... staticConf: cos: region: ap-guangzhou cosOrigin: serverless-nextjs-xxx.cos.ap-guangzhou.myqcloud.com bucket: serverless-nextjs-xxx cdn: domain: static.test.yuga.chat url: https://static.test.yuga.chat
Note: although the CDN domain name has been added here, you still need to configure the CNAME static.test.yuga.chat.cdn.dnsv1.com resolution record manually.
Comparison before and after optimization
So far, the Serverless Next.js application experience has been optimized a lot, and we can use Lighthouse for performance testing to verify our gains. The test results are as follows:
Before optimization:
After optimization:
Before and after comparison, we can clearly see the optimization effect, of course, here is mainly for static resources optimization processing, reducing the cold start. In order to have a better experience of swimming in the lake, we can do more, so we won't discuss it here.
Deploy node_modules based on Layer
As our business becomes more complex, the project volume will become larger and larger, and the node_modules folder will also become larger. Now, every deployment needs to package and compress the node_modules, then upload it, and deploy it to the cloud function together with the business code. In actual development, node_modules does not change much most of the time, but currently it needs to be uploaded every time, which is bound to waste a lot of deployment time, especially when the network is in a bad state, the code upload is even slower.
Since the node_modules folder doesn't change much, can we upload updates only when it changes?
It can be achieved with the help of the ability of Layer.
Before we do that, let's briefly introduce Layer:
With Layer, you can place project dependencies in Layer without having to deploy to cloud function code. Before the function is executed, the files in the Layer will be loaded to the / opt directory (the cloud function code will be mounted to the / var/user/ directory), and / opt and / opt/node_modules will be added to the NODE_PATH, so that even if there is no node_modules folder in the cloud function, the module can be introduced through require ('abc').
It just so happens that the Layer component can help us create the Layer automatically.
When using it, you only need to add the layer folder under the project, and create the layer/serverless.yml configuration as follows:
Org: orgDemoapp: appDemostage: devcomponent: layername: nextjsDemo-layerinputs: region: ap-guangzhou name: ${name} src:.. / node_modules runtimes:-Nodejs10.15-Nodejs12.16
Configuration instructions:
Region: region, which needs to be consistent with the name:Layer name of the cloud function. When binding the cloud function to specify Layer, you need to specify src: specify the directory to be uploaded and deployed to Layer: runtimes: supported operating environment of cloud function.
Execute the deploy Layer command:
Serverless deploy-target=./layerserverless ⚡ frameworkAction: "deploy"-Stage: "dev"-App: "appDemo"-Instance: "nextjsDemo-layer" region: ap-guangzhouname: nextjsDemo-layerbucket: sls-layer-ap-guangzhou-codeobject: nextjsDemo-layer-1594356915.zipdescription: Layer created by serverless componentruntimes:-Nodejs10.15-Nodejs12.16version: 1
It is clear from the output that the Layer component has helped us automatically create a Layer named nextjsDemo-layer with version 1.
Next, how do we automatically bind to our Next.js cloud function?
Referring to the serverless components outputs documentation, you can refer to the outputs of a successfully deployed instance based on Serverless Components (in this case, the output object content of the console). The syntax is as follows:
# Syntax$ {output: [stage]: [app]: [instance]. [output]}
Then we just need to add the layers configuration in the serverless.yml file of the project root:
Org: orgDemoapp: appDemostage: devcomponent: nextjsname: nextjsDemoinputs: src: dist:. / hook: npm run build exclude:-.env-"node_modules/**" region: ap-guangzhou runtime: Nodejs10.15 layers:-name: ${output:$ {stage}: ${app}: ${name}-layer.name} version: ${output:$ {stage}: ${app}: ${name}-layer.version } # static resource related configuration # omitted here.
Note: depending on the use of the deployment instance results of different components, you need to ensure that the three configurations of org,app,stage in serverless.yml are consistent.
Since node_modules has been deployed through Layer, you also need to add ignore deployment to the src.exclude folder.
Then execute the deployment command serverless deploy again, and you will find that the deployment time has been greatly reduced this time, because we no longer need to compress and upload the huge folder node_moduels every time (^ ▽ ^)
Based on the above scheme, I deployed a complete Cnode project, serverless-cnode.
After reading the above, do you have any further understanding of how to deploy an Serverless Next.js application gracefully? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.