Node js TypeScript Fastify EP 04 Routes
In this episode, you will learn how to create routes. Routes are URLs that your API responds to.
What is a route?
A route is a URL path. When someone visits that URL, your API responds. For example, /api/v1/articles is a route.
Step 1 - Create the routes folder
Create a new folder called routes inside the src folder.
Step 2 - Create article route file
Create a new file called article.route.ts inside the src/routes folder.
Step 3 - Write the route code
import { FastifyInstance } from "fastify";
const articleRouter = async (app: FastifyInstance) => {
// This is sample data for testing
const article = {
id: "1",
name: "node.js fastify",
desc: "Fast and easy course for building APIs"
}
// Create a GET route at "/"
app.get(
"/",
() => {
return {
articles: [
article
]
}
}
);
};
export default articleRouter;This code creates a router for articles. It has one route that returns sample data.
Step 4 - Create routes index file
Create a new file called index.ts inside the src/routes folder. This file exports all your routes.
import articleRouter from "./article.route";
export { articleRouter };Step 5 - Register the route in app.ts
Now you need to tell your app to use this route. Update your src/app.ts file.
import fastify, { FastifyServerOptions } from "fastify";
import { articleRouter } from "./routes";
const App = (options: FastifyServerOptions) => {
const app = fastify(options)
app.get("/", async () => "SERVER");
// Register the article router with a prefix
app.register(articleRouter, { prefix: "/api/v1/articles" });
return app
}
export default AppThe prefix means all article routes will start with /api/v1/articles.
Step 6 - Test your route
Stop your server by pressing
CTRL + Cin your terminalStart it again with:
ts-node index.tsOpen Thunder Client and test the route:
http://localhost:5000/api/v1/articles
Result
You should see the article data when you visit the route:
Originally published by me at the dev to - Akkarapon Phikulsri on DEV Community.




