Hello everyone!
In this article I am going to show you how to run a local lan server using Node.js with the help of Fastify framework.
Fastify.js is an alternative to Express.js framework, they define themselves as a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.
Let's dive in right to the code.
First step is we create a very basic Fastify server:
// server.ts
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
fastify.get('/', async function handler (request, reply) {
return 'Hello World!'
})
const start = async () => {
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
The code is self explanatory for those who used to create http servers with Express.js.
Run the server using Node.js:
ts-node server.ts
This will run the server that will be listening at http://127.0.0.1:3000, that means the code works great but unfortunately it only listens to requests from our local machine.
In order to make the server be able to listen to all network interfaces on port 3000 we need to add this host: '0.0.0.0'
to our config so the final code will be like this:
// server.ts
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
fastify.get('/', async function handler (request, reply) {
return 'Hello World!'
})
const start = async () => {
try {
await fastify.listen({ port: 3000, host: '0.0.0.0' })
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
This will logs out Server listening at http://0.0.0.0:3000
, but in order to try to connect to the server from another machine you wouldn't use 0.0.0.0:3000
which is not correct for accessing it from a web browser. The IP address 0.0.0.0
is actually a special address used in server configurations to listen on all network interfaces, but it is not usable to access the server from a client like a browser.
To access your server, you need to use the actual IP address of the machine on which the server is running. You can find it in your machine network configuration.
Because I am using Windows, I can help you with how to find the IP address by following these steps:
- Open CMD.
- Type
ipconfig
and pressEnter
. - Look for the "IPv4 Address" under your network connection. This is your machine's IP address on the LAN.
For example in my case my local IP address was: 192.168.1.8
so you access the server with: 192.168.1.8:3000
I hope you find this article somehow useful. Happy coding!
Top comments (0)