0
# Turbopack Middleware
1
2
Turbopack-specific middleware for handling overlay requests with Turbopack builds, providing optimized source map processing and error handling for Turbopack's build system.
3
4
## Capabilities
5
6
### Turbopack Overlay Middleware
7
8
Create Express middleware specifically designed for Turbopack build integration.
9
10
```typescript { .api }
11
/**
12
* Creates Turbopack-specific overlay middleware
13
* @param project - Turbopack project interface for source operations
14
* @returns Express middleware function optimized for Turbopack
15
*/
16
function getOverlayMiddleware(
17
project: Project
18
): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
19
20
interface Project {
21
/** Turbopack project interface for source map and file operations */
22
// Note: This is a Turbopack-internal interface
23
// Exact methods depend on Turbopack version
24
}
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { getOverlayMiddleware } from "@next/react-dev-overlay/middleware-turbopack";
31
import express from 'express';
32
33
// Assuming you have a Turbopack project instance
34
const turbopackProject = createTurbopackProject();
35
36
const app = express();
37
38
// Setup Turbopack overlay middleware
39
const overlayMiddleware = getOverlayMiddleware(turbopackProject);
40
41
// Use middleware for Turbopack-specific endpoints
42
app.use('/__nextjs_original-stack-frame', overlayMiddleware);
43
```
44
45
### Turbopack Stack Frame Processing
46
47
Create original stack frames optimized for Turbopack's source map format and build system.
48
49
```typescript { .api }
50
/**
51
* Creates original stack frames for Turbopack builds
52
* @param project - Turbopack project instance
53
* @param frame - Turbopack-specific stack frame data
54
* @returns Promise resolving to original stack frame information
55
*/
56
function createOriginalStackFrame(
57
project: Project,
58
frame: TurbopackStackFrame
59
): Promise<OriginalStackFrameResponse | null>;
60
61
interface TurbopackStackFrame {
62
/** File path in Turbopack's module system */
63
file: string;
64
/** Method or function name */
65
methodName: string | null;
66
/** Line number in original source */
67
line: number;
68
/** Column number in original source */
69
column: number | null;
70
/** Whether this frame is from server-side code */
71
isServer: boolean;
72
}
73
74
interface OriginalStackFrameResponse {
75
originalStackFrame: StackFrame;
76
originalCodeFrame: string | null;
77
sourcePackage?: string;
78
}
79
```
80
81
**Usage Examples:**
82
83
```typescript
84
import { createOriginalStackFrame } from "@next/react-dev-overlay/middleware-turbopack";
85
86
// Process Turbopack stack frame
87
async function processTurbopackError(
88
project: Project,
89
stackFrame: TurbopackStackFrame
90
) {
91
try {
92
const originalFrame = await createOriginalStackFrame(project, stackFrame);
93
94
console.log('Original stack frame:', originalFrame.originalStackFrame);
95
console.log('Code frame:', originalFrame.originalCodeFrame);
96
console.log('Source package:', originalFrame.sourcePackage);
97
98
return originalFrame;
99
} catch (error) {
100
console.error('Failed to process Turbopack stack frame:', error);
101
return null;
102
}
103
}
104
105
// Handle multiple stack frames
106
async function processErrorStack(
107
project: Project,
108
frames: TurbopackStackFrame[]
109
) {
110
const processedFrames = await Promise.all(
111
frames.map(frame => createOriginalStackFrame(project, frame))
112
);
113
114
return processedFrames.filter(frame => frame !== null);
115
}
116
```
117
118
## Turbopack Integration Patterns
119
120
### Next.js with Turbopack
121
122
```typescript
123
// next.config.js with Turbopack
124
const { getOverlayMiddleware } = require("@next/react-dev-overlay/middleware-turbopack");
125
126
module.exports = {
127
experimental: {
128
turbo: {
129
// Turbopack configuration
130
},
131
},
132
133
// Custom server integration
134
async rewrites() {
135
return [
136
{
137
source: '/__nextjs_original-stack-frame',
138
destination: '/api/overlay/stack-frame',
139
},
140
];
141
},
142
};
143
```
144
145
### Custom Development Server
146
147
```typescript
148
import express from 'express';
149
import { getOverlayMiddleware } from "@next/react-dev-overlay/middleware-turbopack";
150
151
// Setup custom development server with Turbopack
152
async function setupDevServer() {
153
const app = express();
154
155
// Initialize Turbopack project (implementation specific)
156
const turbopackProject = await initializeTurbopackProject({
157
root: process.cwd(),
158
mode: 'development',
159
});
160
161
// Setup overlay middleware
162
const overlayMiddleware = getOverlayMiddleware(turbopackProject);
163
164
// Mount middleware
165
app.use('/__nextjs_original-stack-frame', overlayMiddleware);
166
app.use('/__nextjs_launch-editor', overlayMiddleware);
167
168
app.listen(3000, () => {
169
console.log('Dev server with Turbopack overlay ready');
170
});
171
}
172
```
173
174
## Differences from Webpack Middleware
175
176
The Turbopack middleware differs from the webpack middleware in several key ways:
177
178
### Source Map Handling
179
180
Turbopack uses a different source map format and provides different APIs for source resolution:
181
182
```typescript
183
// Webpack middleware approach
184
const webpackStats = compiler.getStats();
185
const source = getSourceById(moduleId, compilation);
186
187
// Turbopack middleware approach
188
const originalFrame = await createOriginalStackFrame(project, frame);
189
```
190
191
### Performance Optimizations
192
193
Turbopack middleware is optimized for Turbopack's faster build system:
194
195
- Faster source map resolution
196
- Optimized module resolution
197
- Better integration with Turbopack's incremental compilation
198
199
### Error Context
200
201
Turbopack provides enhanced error context:
202
203
```typescript
204
interface TurbopackStackFrame extends StackFrame {
205
// Additional Turbopack-specific properties
206
// May include module graph information
207
// Enhanced source mapping data
208
}
209
```
210
211
## API Endpoints
212
213
The Turbopack middleware provides the same API endpoints as the webpack middleware but with Turbopack-optimized implementations:
214
215
### Original Stack Frame Endpoint
216
217
**Endpoint:** `GET /__nextjs_original-stack-frame`
218
219
Processes stack frames using Turbopack's source map system for faster and more accurate source resolution.
220
221
### Launch Editor Endpoint
222
223
**Endpoint:** `GET /__nextjs_launch-editor`
224
225
Opens files in external editors with Turbopack's enhanced file resolution.
226
227
## Error Handling
228
229
Turbopack middleware includes enhanced error handling for Turbopack-specific scenarios:
230
231
```typescript
232
// Handle Turbopack compilation errors
233
function handleTurbopackError(error: Error) {
234
// Turbopack errors may have additional context
235
if (error.message.includes('turbo')) {
236
// Handle Turbopack-specific error
237
console.error('Turbopack compilation error:', error);
238
}
239
}
240
```
241
242
## Migration from Webpack
243
244
When migrating from webpack to Turbopack middleware:
245
246
1. Replace webpack-specific configuration with Turbopack project setup
247
2. Update stack frame processing to use Turbopack-specific functions
248
3. Adapt error handling for Turbopack's error format
249
4. Test with Turbopack's development workflow
250
251
```typescript
252
// Before (webpack)
253
import { getOverlayMiddleware } from "@next/react-dev-overlay/middleware";
254
255
const middleware = getOverlayMiddleware({
256
rootDirectory: __dirname,
257
stats: () => webpackStats,
258
serverStats: () => serverStats,
259
edgeServerStats: () => null,
260
});
261
262
// After (Turbopack)
263
import { getOverlayMiddleware } from "@next/react-dev-overlay/middleware-turbopack";
264
265
const middleware = getOverlayMiddleware(turbopackProject);
266
```