Node js TypeScript Fastify EP 03 App
In this episode, you will learn how to organize your code better. We will move the app logic to a separate file.
Why organize code?
When your code grows, it is better to organize it. This makes your code easier to read and maintain. We will create a src folder and put our code there.
Step 1 - Create the src folder
First, create a new folder called src in your project root.
Step 2 - Move app logic to src/app.ts
Create a new file called app.ts inside the src folder. Move the app creation code there.
Code for src/app.ts
import fastify, { FastifyServerOptions } from "fastify";
const App = (options: FastifyServerOptions) => {
const app = fastify(options)
app.get("/", async () => "SERVER");
return app
}
export default AppThis code creates a function called App. This function takes options and creates a Fastify app. It returns the app so you can use it later.
Code for index.ts
Now update your index.ts file. Import the App function and use it to create your app:
import App from "./src/app";
const app = App({
logger: true
})
const PORT = 5000
app.listen({port:Number(PORT)}, (err) => {
if (err) {
app.log.error(err);
process.exit(1)
}
app.log.info(`SERVE ON ${PORT}`)
})What changed?
Before: All your code was in
index.tsAfter: The app logic is in
src/app.tsandindex.tsonly starts the server
This makes your code more organized. When you add more features, you will add them to the src folder.
Originally published by me at the dev to - Akkarapon Phikulsri on DEV Community.



