or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

build-status.mdclient-error-handling.mderror-processing.mdindex.mdturbopack-middleware.mdwebpack-middleware.md

webpack-middleware.mddocs/

0

# Webpack Middleware

1

2

Express middleware for handling overlay requests and source map processing with webpack builds, providing API endpoints for error source mapping and editor integration.

3

4

## Capabilities

5

6

### Overlay Middleware Creation

7

8

Create Express middleware that handles overlay API requests and source map processing.

9

10

```typescript { .api }

11

/**

12

* Creates Express middleware for handling overlay requests

13

* @param options - Configuration options for webpack integration

14

* @returns Express middleware function

15

*/

16

function getOverlayMiddleware(

17

options: OverlayMiddlewareOptions

18

): (req: IncomingMessage, res: ServerResponse, next: () => void) => void;

19

20

interface OverlayMiddlewareOptions {

21

/** Root directory of the project for file resolution */

22

rootDirectory: string;

23

/** Function returning client webpack stats */

24

stats(): webpack.Stats | null;

25

/** Function returning server webpack stats */

26

serverStats(): webpack.Stats | null;

27

/** Function returning edge server webpack stats */

28

edgeServerStats(): webpack.Stats | null;

29

}

30

```

31

32

**Usage Examples:**

33

34

```typescript

35

import express from 'express';

36

import { getOverlayMiddleware } from "@next/react-dev-overlay/middleware";

37

import webpack from 'webpack';

38

39

const app = express();

40

41

// Create webpack compiler instances

42

const clientCompiler = webpack(clientConfig);

43

const serverCompiler = webpack(serverConfig);

44

45

// Setup overlay middleware

46

const overlayMiddleware = getOverlayMiddleware({

47

rootDirectory: process.cwd(),

48

stats: () => clientCompiler.stats,

49

serverStats: () => serverCompiler.stats,

50

edgeServerStats: () => null, // Optional

51

});

52

53

// Use middleware

54

app.use('/__nextjs_original-stack-frame', overlayMiddleware);

55

```

56

57

### Source Map Processing

58

59

Utilities for processing webpack source maps and creating original stack frames.

60

61

```typescript { .api }

62

/**

63

* Creates original stack frames from webpack source maps

64

* @param params - Parameters for stack frame creation

65

* @returns Promise resolving to original stack frame data or null

66

*/

67

function createOriginalStackFrame(params: {

68

line: number;

69

column: number | null;

70

source: any;

71

sourcePackage?: string;

72

moduleId?: string;

73

modulePath?: string;

74

rootDirectory: string;

75

frame: any;

76

errorMessage?: string;

77

clientCompilation?: webpack.Compilation;

78

serverCompilation?: webpack.Compilation;

79

edgeCompilation?: webpack.Compilation;

80

}): Promise<OriginalStackFrameResponse | null>;

81

82

/**

83

* Retrieves source content by module ID from webpack stats

84

* @param isFile - Whether the ID represents a file

85

* @param id - Module ID to retrieve source for

86

* @param compilation - Optional webpack compilation object

87

* @returns Promise resolving to source content

88

*/

89

function getSourceById(

90

isFile: boolean,

91

id: string,

92

compilation?: webpack.Compilation

93

): Promise<Source>;

94

95

interface OriginalStackFrameResponse {

96

originalStackFrame: StackFrame;

97

originalCodeFrame: string | null;

98

sourcePackage?: string;

99

}

100

101

type Source = { map: () => RawSourceMap } | null;

102

103

interface StackFrame {

104

file: string | null;

105

methodName: string | null;

106

arguments: string[];

107

lineNumber: number | null;

108

column: number | null;

109

}

110

```

111

112

**Usage Examples:**

113

114

```typescript

115

import { createOriginalStackFrame, getSourceById } from "@next/react-dev-overlay/middleware";

116

117

// Process stack frames

118

async function processError(stackFrame: StackFrame) {

119

try {

120

const originalFrame = await createOriginalStackFrame();

121

console.log('Original frame:', originalFrame);

122

} catch (error) {

123

console.error('Failed to process stack frame:', error);

124

}

125

}

126

127

// Get source by ID

128

function getModuleSource(moduleId: string, compilation: webpack.Compilation) {

129

const source = getSourceById(moduleId, compilation);

130

if (source) {

131

const sourceMap = source.map();

132

console.log('Source map:', sourceMap);

133

}

134

}

135

```

136

137

### Error Source Analysis

138

139

Analyze and process error sources from stack frames with webpack context.

140

141

```typescript { .api }

142

/**

143

* Extracts error source information from stack frames

144

* @param error - Error object with stack trace

145

* @returns Error source type or null

146

*/

147

function getErrorSource(error: Error): 'server' | 'edge-server' | null;

148

149

/**

150

* Decorates errors with server context information

151

* @param error - Error object to decorate

152

* @param type - Type of server context

153

*/

154

function decorateServerError(error: Error, type: ErrorType): void;

155

156

/**

157

* Creates server errors with proper stack traces and context

158

* @param error - Original error object

159

* @param type - Type of error context

160

* @returns Enhanced error object

161

*/

162

function getServerError(error: Error, type: ErrorType): Error;

163

164

type ErrorType = 'server' | 'edge-server';

165

```

166

167

**Usage Examples:**

168

169

```typescript

170

import { getErrorSource, decorateServerError, getServerError } from "@next/react-dev-overlay/middleware";

171

172

// Analyze error source

173

function analyzeError(error: Error) {

174

const source = getErrorSource(error);

175

176

if (source === 'server') {

177

console.log('Server-side error detected');

178

} else if (source === 'edge-server') {

179

console.log('Edge server error detected');

180

}

181

}

182

183

// Decorate server errors

184

function handleServerError(error: Error) {

185

decorateServerError(error, 'server');

186

throw error; // Error now has additional server context

187

}

188

189

// Create enhanced server error

190

function createEnhancedError(originalError: Error) {

191

const serverError = getServerError(originalError, 'server');

192

return serverError;

193

}

194

```

195

196

### Stack Parsing Utilities

197

198

Parse and process JavaScript stack traces into structured format.

199

200

```typescript { .api }

201

/**

202

* Parses error stack traces into structured StackFrame objects

203

* @param stack - Raw stack trace string

204

* @returns Array of parsed stack frames

205

*/

206

function parseStack(stack: string): StackFrame[];

207

208

interface StackFrame {

209

file: string | null;

210

methodName: string | null;

211

arguments: string[];

212

lineNumber: number | null;

213

column: number | null;

214

}

215

```

216

217

**Usage Examples:**

218

219

```typescript

220

import { parseStack } from "@next/react-dev-overlay/middleware";

221

222

// Parse error stack

223

function processErrorStack(error: Error) {

224

if (error.stack) {

225

const frames = parseStack(error.stack);

226

227

frames.forEach((frame, index) => {

228

console.log(`Frame ${index}:`, {

229

file: frame.file,

230

method: frame.methodName,

231

line: frame.lineNumber,

232

column: frame.column

233

});

234

});

235

}

236

}

237

238

// Filter relevant frames

239

function getRelevantFrames(error: Error): StackFrame[] {

240

const frames = parseStack(error.stack || '');

241

242

// Filter out node_modules frames

243

return frames.filter(frame =>

244

frame.file && !frame.file.includes('node_modules')

245

);

246

}

247

```

248

249

## Middleware API Endpoints

250

251

The overlay middleware provides several API endpoints:

252

253

### Original Stack Frame Endpoint

254

255

**Endpoint:** `GET /__nextjs_original-stack-frame`

256

257

**Query Parameters:**

258

- `isServer` - Boolean indicating server-side error

259

- `isEdgeServer` - Boolean indicating edge server error

260

- `file` - File path from stack frame

261

- `methodName` - Method name from stack frame

262

- `lineNumber` - Line number from stack frame

263

- `column` - Column number from stack frame

264

265

**Response:**

266

```typescript

267

interface OriginalStackFrameResponse {

268

originalStackFrame: StackFrame;

269

originalCodeFrame: string | null;

270

sourcePackage?: string;

271

}

272

```

273

274

### Launch Editor Endpoint

275

276

**Endpoint:** `GET /__nextjs_launch-editor`

277

278

**Query Parameters:**

279

- `file` - File path to open

280

- `lineNumber` - Line number to navigate to

281

- `column` - Column number to navigate to

282

283

## Integration with Development Server

284

285

```typescript

286

// Express server with overlay middleware

287

import express from 'express';

288

import { getOverlayMiddleware } from "@next/react-dev-overlay/middleware";

289

290

const app = express();

291

292

const overlayMiddleware = getOverlayMiddleware({

293

rootDirectory: __dirname,

294

stats: () => webpackStats,

295

serverStats: () => serverWebpackStats,

296

edgeServerStats: () => null,

297

});

298

299

// Mount middleware at expected paths

300

app.use('/__nextjs_original-stack-frame', overlayMiddleware);

301

app.use('/__nextjs_launch-editor', overlayMiddleware);

302

303

app.listen(3000);

304

```