Backend Development 12 min read

Midway 2.0 Unveiled: Key Features and Performance Boosts for Node.js Developers

Midway 2.0 introduces a runtime‑based Hook system, removes compiler constraints, enables faster startup under 2 seconds, supports code reuse, new middleware models, flexible configuration via midway.config.ts, enhanced testing utilities, and broader deployment scenarios including web servers, all backed by open‑source Vite and Prisma integrations.

Taobao Frontend Technology
Taobao Frontend Technology
Taobao Frontend Technology
Midway 2.0 Unveiled: Key Features and Performance Boosts for Node.js Developers

New Features

Midway 2.0 replaces the compiler‑based Hook implementation with a runtime solution using

Node.js AsyncLocalStorage

, eliminating startup latency, syntax limits, and TypeScript compatibility issues while unlocking new possibilities.

1. Reduced Syntax Restrictions

Version 1.0 required strict naming and calling conventions for Hooks, burdening developers. In 2.0 these constraints are removed; Hooks can be used in any function without naming limits.

Example code that now runs:

<code>export async function get () {
  return { type: 'GET' };
}
export async function post (message: string) {
  return { type: 'POST', message };
}</code>

We still recommend naming Hook functions with the

use

prefix for clarity.

2. Code Reuse

Hooks can now be packaged as reusable npm modules, allowing shared libraries across projects.

3. Ultra‑Fast Startup

Version 1.0 performed heavy compilation at launch, causing start times >10 seconds for new projects. Midway 2.0’s pure runtime approach reduces cold start and restart to under 2 seconds, regardless of file count.

The runtime no longer creates

.faas_debug_tmp

cache folders, keeping project directories tidy.

Unit Testing

Midway Hooks now support two testing APIs:

runFunction

for pure function testing and

request

for full HTTP testing.

<code>import { createApp } from '@midwayjs/hooks-testing-library';
import { get, post } from './api';

it('GET', async () => {
  const app = await createApp();
  expect(await app.runFunction(get)).toEqual({ type: 'GET' });
  expect(await app.runFunction(post, '2.0')).toEqual({ type: 'POST', message: '2.0' });
});</code>
<code>import { createApp } from '@midwayjs/hooks-testing-library';
import { get, post } from './api';

it('GET', async () => {
  const app = await createApp();
  const response = await app.request(get);
  expect(response.status).toEqual(200);
  expect(response.type).toEqual('application/json');
  const postResponse = await app.request(post, '2.0');
  expect(postResponse.status).toEqual(200);
  expect(postResponse.type).toEqual('application/json');
});</code>

Plugin‑Based and Functional Configuration

In 1.0, Hooks were tied to the

faas-cli

plugin. In 2.0 they become a first‑class Midway component, usable in any Midway project, whether serverless or traditional web.

<code>import { hooks, createConfiguration } from '@midwayjs/hooks';
import logger from './logger';

export default createConfiguration({
  imports: [
    hooks({
      middleware: [logger],
    }),
  ],
});</code>

Hooks Middleware

Midway 2.0 adds three middleware scopes: global, file‑level, and function‑level (compatible with 1.0).

<code>import { Context } from '@midwayjs/faas';
import { useContext } from '@midwayjs/hooks';

const logger = async (next: any) => {
  const ctx = useContext<Context>();
  console.log(`<-- [${ctx.method}] ${ctx.url}`);
  const start = Date.now();
  await next();
  const cost = Date.now() - start;
  console.log(`[${ctx.method}] ${ctx.url} ${cost}ms`);
};</code>
<code>import { ApiConfig } from '@midwayjs/hooks';
import logger from './logger';

export const config: ApiConfig = {
  middleware: [logger],
};

export default async (message: string) => {
  return { type: 'POST', message };
};</code>

Project Configuration

Midway 2.0 introduces

midway.config.ts

to replace the limited

f.yml

. Developers can define source directories, routes, and devServer options via

defineConfig

.

<code>import { defineConfig } from '@midwayjs/hooks';

export default defineConfig({
  source: 'src/apis',
  routes: [
    { baseDir: 'lambda', basePath: '/api' },
  ],
});</code>

File routing is now unified under this config, with defaults of

/src/apis

(customizable) and support for pure API projects (

/src

).

DevServer can ignore specific patterns, e.g., static assets.

Multi‑Scenario Support

Midway 2.0 supports pure API projects, web server deployments (using Koa as the underlying framework), and integrates with popular tools like Vite and Prisma.

Example of adding a Koa body parser globally:

<code>import { hooks, createConfiguration } from '@midwayjs/hooks';
import bodyParser from 'koa-bodyparser';

export default createConfiguration({
  imports: [
    hooks({
      middleware: [bodyParser()],
    }),
  ],
});</code>

When running on a web server,

useContext

provides a Koa

Context

object.

<code>import { useContext } from '@midwayjs/hooks';
import { Context } from '@midwayjs/koa';

function useKoaContext() {
  return useContext<Context>();
}

export default async () => {
  return {
    message: 'Hello World',
    method: useKoaContext().method,
  };
};</code>

Open‑Source Ecosystem

Midway 2.0 is fully open source (https://github.com/midwayjs/midway) and embraces modern tooling such as Vite for fast front‑end builds and Prisma for type‑safe database access.

performanceTestingBackend Developmentconfigurationnode.jshooksMidway
Taobao Frontend Technology
Written by

Taobao Frontend Technology

The frontend landscape is constantly evolving, with rapid innovations across familiar languages. Like us, your understanding of the frontend is continually refreshed. Join us on Taobao, a vibrant, all‑encompassing platform, to uncover limitless potential.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.