- Functional Programming
- DDD
- NodeJS
How I refactored Notion Blog: a scalable functional architecture with Node.js, Express and DDD
I reworked notion-blog with a functional architecture in Node.js and Express, inspired by DDD. Now the code is cleaner, testable and ready to grow.
Building the first part of the notion-blog code has been relatively simple so far. Basically, I spun up an HTTP server with Express, wrote the route code directly in the framework's setup (there are only a few routes for now) and wired up the calls between the Notion and Vercel APIs. Nothing too complex. I think we can all agree on that, right?
The real challenge starts when we look ahead. At some point, this tool may evolve and add new features β like a read counter, estimated reading time, a newsletter and other integrations.
As the code grows, so does the complexity. Testing, debugging and maintaining the system become harder and, inevitably, frustrating tasks. That's exactly the point where many small projects end up abandoned: the difficulty of adding small features makes the whole process heavy and discouraging.
Table of contents
Goals of the RefactoringMaking the changesIntroducing the functional paradigmImplementing a pure HandlerReal gains from this structural change1. Replacing exceptions with explicit results2. Dependency inversion through Reader3. Functional Core, Imperative Shell4. Ports & Adapters (Hexagonal Architecture)5. Introducing generic interfaces and contracts6. Isolating asynchronous effects7. Standardization and functional composition8. Separation of responsibilities9. Documenting the domain through typesIn shortApplying DDD conceptsThe Repository interfaceImplementing RepositoriesIn Memory RepositoryAccessing the Notion API through the Repository patternThe direct benefitRoadmap and next stepsConclusion
You can check out the full project in the project repository
Refactoring the application's code isn't just an exercise in technical showmanship. It's a necessity β a fundamental step to ensure the system can keep evolving and stay maintainable.
Since this is a project where I set the guidelines, I use functional programming as the foundation. I believe this paradigm makes code more predictable, testable and safe. If we look at the tests we've written so far, we can see that we have to rely on a lot of mocks β replacements for libraries that are coupled to and depended on inside our little system. That's a clear sign that we can improve the application's design.
Goals of the Refactoring
- Reduce coupling in the code (fewer direct dependencies)
- Make the code cleaner and more readable
- Split responsibilities clearly
- Apply a functional pattern that makes collaboration between developers easier
Making the changes
Introducing the functional paradigm
Below is an example of the application's current code. Basically, all the logic happens inside the Express framework's
requestHandler structure. That means that if we try to change any part of it, there's a good chance we'll break the application.app.get('/post/:slug', async (req, res) => { try { const { slug } = req.params const pageId = await getPostIdWithSlug({ slug }) if (!pageId) return res.status(400).json({ message: 'Bad request' }) const page = await getPostData({ pageId }) if (!page) return res.status(404).json({ message: 'Post not found' }) return res.json(page) } catch (e) { // eslint-disable-next-line no-console console.error(e) return res.status(500).json({ error: 'Internal server error' }) } })
What does functional programming tell us about pure functions?
Pure functions have no side effects and, precisely because of that, they're predictable and testable. That's where the refactoring begins: turning the handler above into a pure function.
To do that, I created the following interfaces and types:
export interface Tagged<V extends string> { readonly __tag: V } export interface Request<B = any> extends Tagged<'request'> { ctx: Context body: B headers: IncomingHttpHeaders } export interface Response<B = any> extends Tagged<'response'> { status: number body: B } export interface Reader<E, A> { (env: E): A } export interface ReaderTask<E, A> { (env: E): Promise<A> } export type Result<E, A> = Reader<E, A> | ReaderTask<E, A> export type HandlerResult<E> = Result<E, Response> interface Handler<E = {}> extends Tagged<'handler'> { (request: Request): HandlerResult<E> }
Implementing a pure Handler
interface Env { covers: Readable<Repository<PostCover>> posts: Queryable<Repository<Post>> } export const getPostDataHandler = Handler( request => async ({ covers, posts }: Env) => { const { slug } = request.ctx.params const r1 = await getPostIdWithSlug({ slug })({ covers }) if (isLeft(r1)) return Response({ status: 400, body: { message: 'Bad request' } }) const r2 = await getPostData({ id: r1.value })({ posts }) if (isLeft(r2)) return Response({ status: 404, body: { message: 'Post not found' } }) return Response.ok(r2.value) }, )
For this handler to work within the Express framework, we create an adapter layer:
export function expressHandlerAdapter<E = {}>( handler: Handler<any>, env: E = {} as E, ): RequestHandler { return (request, response) => { try { const res = handler(requestAdapter(request))(env) if (res instanceof Promise) { return res.then(r => response.status(r.status).json(r.body)) } return response.status(res.status).json(res.body) } catch (e) { console.error(e) return response.status(500).json({ message: 'Internal server error!' }) } } }
With this change, as long as the handlers are well written β clean and free of direct dependencies β, the functions become pure, which improves predictability, testability and composition.
Real gains from this structural change
The refactoring goes far beyond a cosmetic change to the code.
It introduces functional programming concepts that make the system safer, more predictable and more sustainable.
Below are the main gains β and what each one means in practice.
1. Replacing exceptions with explicit results
Instead of handling errors with
try/catch blocks, the application now works with explicit result types (Result<A> = FailedResult | SuccessfulResult<A>).This approach follows the Railway-Oriented Programming model, in which success and error flows are composable and typed.
The result is safer, more readable error handling, with no reliance on runtime exceptions.
2. Dependency inversion through Reader
The
Handler<E, A> function now returns a Reader (or ReaderTask), which injects the dependency environment (E) at execution time.That means the function no longer creates its own dependencies β they're provided from the outside.
This pattern reflects the Inversion of Control principle, making the code more modular, testable and flexible to change.
3. Functional Core, Imperative Shell
The business logic (core) is now completely pure, with no side effects.
The imperative part β responsible for dealing with HTTP requests, statuses and JSON responses β is isolated in the Express adapter.
This model (functional core, imperative shell) ensures the domain can be tested independently, keeping side effects only at the edges of the system.
4. Ports & Adapters (Hexagonal Architecture)
The
expressHandlerAdapter works as an adapter between the HTTP world and the functional domain.With this intermediate layer, the application's core becomes framework-agnostic, allowing future migrations (for example, swapping Express for Fastify) without major impact on the main code.
5. Introducing generic interfaces and contracts
Creating the
Handler<E, A> and HandlerResult<E, A> interfaces establishes clear contracts for communication between modules.This formalization reduces coupling between components and makes it easier to write mocks and stubs for tests, while explicitly documenting the expected behavior of each function.
6. Isolating asynchronous effects
By using
ReaderTask, asynchronous effects (like API or database calls) are described, not executed right away.This separation lets the code be tested deterministically, since the effects only happen when the adapter explicitly runs them.
7. Standardization and functional composition
With
Result + Reader(Task), the code becomes composable β in other words, functions can be chained without creating pyramids of try/catch or multiple if/else.This standardization creates a cleaner, more predictable data flow that's easier to maintain.
8. Separation of responsibilities
Each part of the application now has a single responsibility:
- The handler describes the use case (pure domain)
- The adapter deals with transport and the HTTP protocol
- The
Eenvironment groups external dependencies (like a DB, a cache or APIs)
This split makes the system more modular and scalable, simplifying maintenance and evolution.
9. Documenting the domain through types
The
FailedResult and SuccessfulResult types explicitly represent the possible states of an operation.This works as living documentation of the domain, checked by the compiler.
A developer quickly understands the expected behavior of each function without having to dig into its internals.
In short
This functional approach not only improves the system's testability and predictability, it also prepares it to grow sustainably.
The application now has an architecture that's clearer, safer and less dependent on frameworks β exactly the kind of foundation that separates projects that keep evolving from the ones that become hard to maintain.
Applying DDD concepts
Instead of building an application fully aligned with Domain-Driven Design (DDD) and all its layers and elements, I chose to bring in only the concepts that make sense within the functional paradigm and that help with organizing and reusing code.
The idea isn't to follow DDD to the letter, but to take advantage of some of its principles β especially the ones that strengthen domain isolation, clear contracts and the testability of the system's critical parts.
The Repository interface
The first concept I applied was the Repository pattern.
It abstracts data access and lets us swap external implementations (like APIs or databases) for in-memory versions β something essential for predictable unit tests that don't depend on external services.
Take a look at the snippet below:
export const URI = 'repository' export type URI = typeof URI export type RepositoryResult<E> = E | Promise<E> export interface Repository<E extends Entity = any> extends Tagged<URI> { readonly get: (id: string) => RepositoryResult<E | undefined> readonly set: (entity: E) => RepositoryResult<E> readonly remove: (e: Identifier) => RepositoryResult<void> readonly query: (q: Query<E>) => RepositoryResult<E[]> } // Helper Types export interface Readable<R extends Repository> extends Tagged<URI> { readonly get: R['get'] } export interface Queryable<R extends Repository> extends Tagged<URI> { readonly query: R['query'] }
With this structure, the application works with generic, predictable interfaces.
That makes it easier to isolate responsibilities and makes the code agnostic to the data source, preserving functional purity and reducing coupling.
Implementing Repositories
In Memory Repository
Below is the implementation of an in-memory repository β useful for tests, prototyping and quick behavior checks, with no need to integrate with Notion or any other backend.
export function InMemoryRepository<E extends Entity>({ repository = [], idProvider = Id(), }: Config<E> = {}): Repository<E> { let repo = [...repository] function get(id: string) { return repo.find(el => el.id === id) } // Create or Save function set(entity: E) { const now = new Date() const e = { ...entity } as any if (!entity.id) { e.id = idProvider() e.created_at = now } else { repo = repo.filter(el => el.id !== e.id) } e.updated_at = now repo = repo.concat(e) return e } function remove({ id }: Identifier) { repo = repo.filter(el => el.id !== id) } function query({ where, sorts, cursor, limit }: Query<E>) { let r = [...repo] if (sorts) r.sort(applySorts(sorts)) if (where) r = r.filter(applyWhere(where)) if (limit) { const start = cursor ? Number(cursor) * limit : 0 const end = cursor ? (Number(cursor) + 1) * limit : limit r = r.slice(start, end) } return r } return applyTag('repository')({ get, set, remove, query, }) }
This implementation drastically simplifies swapping dependencies during unit tests, letting us simulate behavior in a controlled and predictable way.
Accessing the Notion API through the Repository pattern
The same pattern is also applied to accessing the Notion API.
Instead of scattering direct API calls around, everything now goes through a NotionRepository, which implements only the methods it needs.
You can check out the full implementation in the project repository
Since the current API access is limited to queries, the implementation uses the
Queryable<Repository<E>> helper type:export function NotionRepository<E extends Entity>({ auth_token, collection_id, converter, propertyMapper, client = auth => new Client({ auth, }), }: Config<E>): Queryable<Repository<E>> { const notion = client(auth_token) const query = async ({ where, limit, sorts: s }: Query<E>) => { const filter = where ? filterMapper({ whereAdapter: whereAdapter(propertyMapper), })(where) : undefined const sorts = s ? sortMapper({ propertyMapper })(s) : undefined const result = await notion.dataSources.query({ data_source_id: collection_id, filter, sorts, page_size: limit, }) return result.results .filter(p => p.object === 'page' && !(p as any).in_trash) .map(converter.from) } return applyTag('repository')({ query, }) }
The direct benefit
Adapting the Repository pattern to a functional context brings a clear advantage: it's possible to test and evolve the domain without depending on any external infrastructure.
The domain becomes pure and predictable, while the adapters (like NotionRepository) take care of dealing with the outside world.
Roadmap and next steps
- Improve the design to reflect a more modern and consistent blog.
- Add performance monitoring scripts for the content.
- Use a bundler to optimize the application's size within the monorepo.
- Refactor the code to decouple modules and prepare the application for future replacements without major impact.
Conclusion
Refactoring the notion-blog code was more than a technical initiative β it was an exercise in maturing its architecture, purpose and long-term vision. The decision to adopt the functional paradigm and DDD-inspired principles didn't come from an immediate need, but from understanding that a project's sustainability comes from the clarity of its foundations.
By making the code more predictable, isolated and safe, we created fertile ground for it to evolve. Every new module, integration or feature can be added without compromising the whole β one of the biggest wins in any growing system.
This refactoring marks a turning point: we stopped seeing notion-blog as just an integration between APIs and started treating it as a system with its own domain, with clear rules, well-defined layers and room for collaboration.
More than code, this process reinforces a philosophy:
building software isn't just about solving technical problems, but about creating structures that stand up to time, to change and to people.
What comes next β the roadmap β isn't just a to-do list, but a natural continuation of this process. Design improvements, monitoring, build optimization and module decoupling are direct extensions of what was established here: a solid foundation to evolve with confidence.
In short:
The notion-blog refactoring isn't an endpoint.
It's the start of a new stage β more mature, more deliberate and much better prepared to grow.
Yago MarinhoSenior Software Engineer. I build AI-powered products, from design to deploy.