Skip to content

Commit

Permalink
Expose TS type for onRequestError (#67859)
Browse files Browse the repository at this point in the history
## What

Expose the TS types for onRequestError API

### API
```ts
type RequestErrorContext = {
    routerKind: 'Pages Router' | 'App Router';
    routePath: string;
    routeType: 'render' | 'route' | 'action' | 'middleware';
    renderSource?: 'react-server-components' | 'react-server-components-payload' | 'server-rendering';
};

export declare namespace Instrumentation {
    type onRequestError = (error: unknown, errorRequest: Readonly<{
    method: string;
    url: string;
    headers: NodeJS.Dict<string | string[]>;
}>, errorContext: Readonly<RequestErrorContext>) => void | Promise<void>;
```

### Usage

```ts
// instrumentation.ts
import { type Instrumentation } from 'next'

export const onRequestError: Instrumentation.onRequestError = (
  err,
  request,
  context
) => {
  //...
}
```
  • Loading branch information
huozhi committed Jul 17, 2024
1 parent 8f08c7c commit 517f0e0
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
4 changes: 4 additions & 0 deletions packages/next/src/server/instrumentation/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ export type InstrumentationModule = {
register?(): void
onRequestError?: InstrumentationOnRequestError
}

export namespace Instrumentation {
export type onRequestError = InstrumentationOnRequestError
}
2 changes: 2 additions & 0 deletions packages/next/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export type {
ResolvedViewport,
} from './lib/metadata/types/metadata-interface'

export type { Instrumentation } from './server/instrumentation/types'

/**
* Stub route type for typedRoutes before `next dev` or `next build` is run
* @link https://nextjs.org/docs/app/building-your-application/configuring/typescript#statically-typed-links
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
export function onRequestError(err, request, context) {
import { type Instrumentation } from 'next'

export const onRequestError: Instrumentation.onRequestError = (
err,
request,
context
) => {
fetch(`http://localhost:${process.env.PORT}/write-log`, {
method: 'POST',
body: JSON.stringify({
message: err.message,
message: (err as Error).message,
request,
context,
}),
Expand Down

0 comments on commit 517f0e0

Please sign in to comment.