Today I'll show you step by step how easy it is to deploy a Fastify server on Azure Function.
Steps to create a Fastify server
Project folder creation
mkdir azure-fastify && cd azure-fastify
Initialize npm
npm init -y
Install fastify
npm i fastify
package.json
You should find this file inside your project, it was created by npm
{
"name": "azure-fastify",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"fastify": "^4.10.2"
}
}
I added the script to launch the Fastify server "start": "node index.js" and "type": "module"
index.js
Let's create our code for the Fastify server
import Fastify from 'fastify';
const fastify = Fastify({
logger: true,
});
fastify.get('/', async (request, reply) => {
return { randomNumber: Math.random() };
});
const start = async () => {
try {
const port = process.env.port || 8080;
await fastify.listen({ port, host: '0.0.0.0' }, () =>
console.log('SERVER LISTENING AT PORT : ' + port)
);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
Here we are creating our Fastify server which responds to the port specified in the environment variables or as an alternative to 8080.
It exposes a JSON with a random number inside.
Local Run
Through the npm run start command we can test our server locally.
Here is the local result:
Steps to deploy on Azure
Install Azure App Service extension
Once the extension is installed we will have this new icon in VSCode
Login into Azure
By pressing on the login button, we are taken to the browser to log in with our Azure account.
You need to have an Azure account, free plan works well for this example.
Once logged in you can go back to VSCode
Creation of a new Web App
We use the following command to create our application on Azure
We need to enter the name of our application
We need to select Node 18 LTS
Let's select Free pricing
The application will be created automatically
Once the application has been created, press the Deploy button
Let's select the project folder
After the deployment let's see our app on Azure
🎉 Wow! We deployed together how to create a server locally with Fastify and we deployed it via Azure 👏
You can follow me on Twitter, where I'm posting or retweeting interesting articles.
I hope you enjoyed this article, don't forget to give ❤️.
Bye 👋
Top comments (1)
Nice tutorial and write up!