How to deploy a Fastify app
Run a Fastify server on Schokr. Fastify listens on localhost by default, so set host to 0.0.0.0 and use your allocated port.
Updated · 1 min read
Fastify listens on localhost by default, which means it is unreachable on a hosted server. To deploy it on Schokr, pass host: '0.0.0.0' and your allocated port to fastify.listen().
1. Write your server
server.js:
import Fastify from 'fastify'
const app = Fastify({ logger: true })
app.get('/', async () => ({ status: 'ok' }))
const port = Number(process.env.APP_PORT || 3000)
try {
await app.listen({ host: '0.0.0.0', port })
} catch (err) {
app.log.error(err)
process.exit(1)
}
package.json:
{
"name": "my-fastify-app",
"type": "module",
"main": "server.js",
"scripts": { "start": "node server.js" },
"dependencies": { "fastify": "^5.0.0" }
}
Fastify 5 needs Node.js 20 or newer. If your server runs an older Node.js version, use Fastify 4 or check whether your server's Startup settings let you pick a newer version.
2. Deploy on Schokr
- Create a server with the Node.js template in the console.
- Note the port in the Network section.
- Upload
server.js,package.jsonandpackage-lock.jsonwith the file manager. Do not uploadnode_modules. - Put the port in a
.envfile (APP_PORT=<your-port>) and start Node with--env-file=.env, or use thedotenvpackage. See environment variables. - Set the main file to
server.jsin your server's Startup settings. - Start the server.
3. Check the logs
With logger: true, Fastify prints a JSON line when it is ready:
{"level":30,"msg":"Server listening at http://0.0.0.0:25571"}
If you see 127.0.0.1 there instead, the host option is not being applied. Open http://<server-address>:<port> to test.
Useful plugins
| Need | Plugin |
|---|---|
| CORS for browser clients | @fastify/cors (see CORS basics) |
| Serve static files | @fastify/static |
| Rate limiting | @fastify/rate-limit |
| WebSockets | @fastify/websocket (see WebSockets) |
Behind a proxy
If you place a reverse proxy or Cloudflare in front of your app, enable trustProxy so client IPs are read from the forwarded headers:
const app = Fastify({ logger: true, trustProxy: true })
Troubleshooting
EADDRINUSE: another process or a second listen call is using the port. See port errors.ERR_REQUIRE_ESMorCannot use import statement outside a module: add"type": "module"topackage.json, or userequiresyntax.- Crashes on start: see app crashes on start.