Fastify starting the server
Fastify tutorial in 4 parts
- Part 1: starting the server ๐ You are here
- Part 2: first route
- Part 3: render view with Amedia Component
- Part 4: server testing
First we need to install packages:
npm i fastify
(or what ever package manager youยดre using)
With that out of the way, it's time to creat instance of our server. Let's create a file called app.js
. Inside write the following code:
import Fastify from 'fastify';
const app = Fastify({
logger: true,
});
app.listen({ port: 3000 }, function (err, address) {
if (err) {
app.log.error(err);
process.exit(1);
}
console.log('Server is now listening on ${address}');
});
With that done, run you server with node app.js
. You should now see a message that your server is listening on wich address, port, etc.
Fastify supports async/await
out of the box, and we can do som adjustments to our code here. Instad of writing
app.listen({ port: 3000 }, function (err, address) {
if (err) {
app.log.error(err);
process.exit(1);
}
console.log('Server is now listening on ${address}');
});
We can write this
try {
const address = await app.listen({ port: 3000 });
console.log('Server is now listening on ${address}');
} catch (err) {
app.log.error(err);
process.exit(1);
}
Now our code is more concise and is not relying on callbacks.
In order to test our code (we'll come back to this later) we would like to be able to export our instance. Now let's refactor our code. In app.js
, write following:
import Fastify from 'fastify';
export function buildApp(args = {}) {
const app = Fastify({
logger: true,
});
return app;
}
This exports a function now that creates an app
instance. It takes arguments in as we will need it later.
Now create a new file called index.js
. In this file, we would create our app
instance:
import { buildApp } from './app.js';
const app = buildApp();
try {
const address = await app.listen({ port: 3000 });
console.log('Server is now listening on ${address}');
} catch (err) {
app.log.error(err);
process.exit(1);
}
Now instead of running app.js
, run our newly created index.js
and you'll see that the server is running.
Congrats ๐ฅณ You've created your first Fastify server. It is missing som key ingredients and we will look how to season this app this those ingredients in the next post.
Fastify tutorial in 4 parts
- Part 1: starting the server โ
- Part 2: first route ๐ Your next adventure
- Part 3: render view with Amedia Component
- Part 4: server testing