Announcing Matterhorn 🏔 – A Node.js API Framework for the Modern Web

Node.js has taken the web development world by storm since its creation in 2009. As of 2023, Node.js is used by over 50% of professional developers, powering everything from small hobby projects to massive enterprise applications. Its event-driven, non-blocking I/O model makes it perfectly suited for building scalable network applications, and nowhere is this more apparent than in the realm of web APIs.

However, while Node.js provides a solid foundation, it is still a relatively low-level platform. Developers are responsible for pulling together the various components needed for a production-grade API, including web frameworks, database integrations, authentication strategies, testing and build pipelines, and more. This process can be time-consuming and overwhelming, especially for teams looking to rapidly prototype and iterate on new ideas.

Enter Matterhorn, a new open-source API framework that aims to streamline Node.js API development for the modern web. Matterhorn provides a complete set of tools and best practices out of the box, allowing developers to focus on writing business logic instead of spending cycles on configuration.

TypeScript First

One of Matterhorn‘s core tenets is putting TypeScript front and center. TypeScript, a typed superset of JavaScript developed by Microsoft, has seen explosive growth in recent years. According to the 2022 State of JS Survey, 75% of respondents are using TypeScript and would use it again, with another 15% interested in learning it.

The benefits of TypeScript for API development are immense. The rich type system allows specifying clear contracts between different parts of your codebase and catches whole classes of bugs at compile time. Intelligent code completion and instant feedback speed up development cycles. Refactoring becomes a breeze with the TypeScript compiler guiding the way.

Matterhorn is built from the ground up with TypeScript in mind. The entire codebase is written in TypeScript, and the framework provides a preconfigured TypeScript environment with sensible defaults optimized for API development. Developers can start writing type-safe code from day one without worrying about the complexities of build tool configuration.

Blazing Fast with Fastify

At the heart of any API framework is the web server that routes incoming requests to the appropriate handler. For Matterhorn, that web server is Fastify.

Fastify is a high-performance, low-overhead web framework for Node.js. In the TechEmpower Web Framework Benchmarks, Fastify consistently ranks as one of the fastest web frameworks across various languages, capable of serving upwards of 150,000 requests per second.

But Fastify is more than just fast. It provides a nice balance of performance and productivity features, including automatic request/response serialization, JSON schema-based validation, lifecycle hooks, and a powerful plugin architecture. Matterhorn leverages these features to provide a delightful developer experience.

Here‘s what a basic route handler looks like in Matterhorn:

// controllers/user.ts

import { FastifyInstance } from ‘fastify‘
import { CreateUserInput } from ‘../schemas/user‘

export default async function userController(server: FastifyInstance) {
  server.post<{
    Body: CreateUserInput
  }>(‘/users‘, {
    schema: {
      body: CreateUserInput,
      response: {
        201: CreateUserInput
      }
    },
    handler: async (request, reply) => {
      const { username, email } = request.body

      // TODO: save to database

      reply.status(201).send({ username, email })
    }
  })
}

In this example, we define a POST /users route for creating a new user. The CreateUserInput type, imported from a shared schema file, specifies the expected shape of the request body. Fastify automatically validates incoming requests against this schema, returning a 400 error if the payload is malformed.

Inside the route handler, we destructure the validated username and email fields from the request body. The handler would then save these to a database (not shown) and return a 201 Created response with the original input echoed back.

With Matterhorn, this concise and expressive style of route definition is the default. Developers can focus on the core logic unique to their application while the framework handles the mundane details.

Testing and Quality Assurance

Automated testing is a crucial part of any serious software development effort, and APIs are no exception. Matterhorn includes a comprehensive testing setup out of the box, powered by the Jest test runner.

Jest has rapidly gained popularity for its simplicity, performance, and powerful snapshot testing features. Matterhorn preconfigures Jest with defaults well-suited for API testing and provides utilities for creating test Fastify server instances.

Here‘s what a test for the /users route handler might look like:

// tests/controllers/user.test.ts

import { createServer } from ‘../../src/server‘
import { CreateUserInput } from ‘../../src/schemas/user‘

const testUserInput: CreateUserInput = {
  username: ‘test_user‘,
  email: ‘[email protected]‘
}

describe(‘POST /users‘, () => {
  let server: ReturnType<typeof createServer>

  beforeEach(() => {
    server = createServer()
  })

  it(‘creates a new user‘, async () => {
    const response = await server.inject({
      method: ‘POST‘,
      url: ‘/users‘,
      payload: testUserInput,
    })

    expect(response.statusCode).toBe(201)
    expect(response.json()).toEqual(testUserInput)
  })
})

In this test, we create a test Fastify server instance and use its inject method to simulate an HTTP request to our /users route, passing in a test user payload. We then assert that the response status code is 201 and that the response body matches the input.

Running npm test will execute the full test suite, providing rapid feedback on the health of the application. Matterhorn also sets up a GitHub Actions workflow for continuous integration, ensuring tests are run on every push and PR.

In addition to testing, Matterhorn enforces code quality standards with ESLint. The provided ESLint configuration extends the recommended rule sets for TypeScript and Fastify, helping catch common gotchas and maintain a consistent code style across the project.

Designed for the Real World

Matterhorn‘s feature set has been carefully curated based on real-world needs of production Node.js deployments. Out of the box, Matterhorn supports:

  • Environment-Based Configuration: Separate configuration files for development, testing, and production environments, easily managed through environment variables.

  • Logging: Structured logging with Pino, a low-overhead logger optimized for Node.js.

  • Database Integration: Support for connecting to PostgreSQL, MongoDB, and other databases via TypeORM and Mongoose, with sample models and migrations included.

  • Authentication: Built-in JWT authentication and support for fine-grained role-based access control.

  • API Documentation: Automatic OpenAPI (Swagger) documentation generation based on your Fastify route schemas.

  • Health Checks: A preconfigured /healthz endpoint for easy integration with Kubernetes and other orchestration platforms.

  • Docker Ready: A Dockerfile and sample Kubernetes manifests for containerized deployments.

Matterhorn has been battle-tested in production at companies large and small. The maintainers have distilled years of experience building and deploying Node.js APIs into a cohesive framework that gets out of your way and lets you ship faster.

Get Started in Minutes

Despite its extensive feature set, getting started with Matterhorn is designed to be a breeze. The project provides an interactive CLI for scaffolding new API projects:

$ npx matterhorn new my-api
$ cd my-api
$ npm install
$ npm run dev

This will create a new Matterhorn project in the my-api directory, install dependencies, and start the development server. The CLI prompts for some basic configuration options and sets up a project structure following best practices:

my-api
├── src
│   ├── schemas         # TypeScript schemas shared across your application 
│   ├── controllers     # Route handlers
│   ├── services        # Business logic and external integrations  
│   ├── models          # Database models and ORMs
│   └── index.ts        # Server entry point
├── tests               # Jest tests
├── package.json
└── matterhornfile.ts   # Matterhorn configuration file

The development server hot-reloads on changes, so you can start implementing your API endpoints and see the results immediately. The Matterhorn CLI also provides commands for common tasks like running migrations, generating documentation, and deploying to production.

A Bright Future

Matterhorn is under active development, with an ambitious roadmap for the future. Some highlights:

  • GraphQL Support: First-class support for standing up a GraphQL API alongside or in place of REST, with tools for generating resolvers from your TypeScript schemas.

  • Serverless Deployments: Adapters for running Matterhorn projects in serverless environments like AWS Lambda and Google Cloud Functions.

  • Expanded Database Support: Robust integrations for additional databases and ORMs, including Redis, SQLite, Prisma, and more.

  • Plugin Ecosystem: A plugin system to allow easy extension of the core Matterhorn framework with custom integrations and functionality.

  • Admin Dashboard: An auto-generated admin UI for managing your API and viewing request metrics and logs.

Of course, as an open-source project, the future of Matterhorn will be driven by its community. We welcome contributions of all kinds, from bug reports and feature requests to documentation improvements and code submissions.

Conclusion

Matterhorn represents a new chapter in the story of Node.js API development. By providing a complete, opinionated framework for building production-ready APIs, Matterhorn aims to empower developers to ship faster and with confidence.

Whether you‘re a seasoned Node.js veteran or just getting started with server-side TypeScript, Matterhorn has something to offer. Its carefully curated set of tools and conventions, combined with a focus on developer experience and real-world performance, make it a compelling choice for projects big and small.

We‘re excited to see what the community will build with Matterhorn. To get started, head over to the GitHub repository, try out the interactive CLI, and join the conversation on Discord. Let‘s build the future of web APIs together!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *