Choose Your Adventure: HTTP Servers in TypeScript

server
adapter

This post adapts to your choices. Pick a server framework and watch the code animate between implementations.

Server framework:

Getting started🔗

First, create a new project and install dependencies:

terminal
mkdir my-api && cd my-api
npm init -y
npm i express
npm i -D typescript tsx @types/express

Hello world🔗

Let's create a simple server that responds with "Hello world!":

src/index.ts
import express from 'express'
const app = express()
app.get('/', (req, res) => {
res.send('Hello world!')
})
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`Express started on http://localhost:${port}`)
})

Express is imported, then an instance is created and saved as app. The app.get() method registers a route handler for GET requests to /.

Adding a route with parameters🔗

Now let's add a route that accepts a name parameter:

src/index.ts
import express from 'express'
const app = express()
app.get('/', (req, res) => {
res.send('Hello world!')
})
app.get('/:name', (req, res) => {
res.send(`Hello ${req.params.name}!`)
})
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`Express started on http://localhost:${port}`)
})

Test it:

terminal
curl localhost:3000/foo

You should see "Hello foo!" regardless of which framework you chose.

The database layer🔗

Now let's add a database. We'll use PostgreSQL.

Query approach:
src/db.ts
import { Kysely, PostgresDialect } from 'kysely'
import type { DB } from 'kysely-codegen'
import pg from 'pg'
export const db = new Kysely<DB>({
dialect: new PostgresDialect({
pool: new pg.Pool({
connectionString: process.env.DATABASE_URL,
}),
}),
})

Kysely is a type-safe query builder. Combined with kysely-codegen, it introspects your database and generates TypeScript types that match your schema.

Data methods🔗

Now let's create functions to interact with a movies table:

src/movies.ts
import { db } from './db'
export async function list() {
return db
.selectFrom('movies')
.selectAll()
.execute()
}
export async function create(title: string, released: number) {
return db
.insertInto('movies')
.values({ title, released })
.returningAll()
.executeTakeFirstOrThrow()
}

Wiring it all together🔗

Finally, let's connect the routes to the database methods. This is where both choices come together:

src/index.ts
import express from 'express'
import * as movies from './movies'
const app = express()
app.use(express.json())
app.get('/api/movies', async (req, res) => {
res.json(await movies.list())
})
app.post('/api/movies', async (req, res) => {
const { title, released } = req.body
res.json(await movies.create(title, released))
})
const port = process.env.PORT || 3000
app.listen(port, () => {
console.log(`Express started on http://localhost:${port}`)
})

Notice how the src/index.ts changes with your server choice, while src/movies.ts and src/db.ts change with your adapter choice — the two dimensions are independent!

Comments

GitHub sign-in is not configured yet, so posting is temporarily unavailable.

  • Loading...