Skip to content

Commit

Permalink
[example] multiple exports setup (vercel#131)
Browse files Browse the repository at this point in the history
* add multiple export example

* fix dependency versions
  • Loading branch information
kakadiadarpan authored Nov 13, 2024
1 parent 087601a commit faeb349
Show file tree
Hide file tree
Showing 26 changed files with 773 additions and 20 deletions.
3 changes: 3 additions & 0 deletions apps/multiple-exporters/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
36 changes: 36 additions & 0 deletions apps/multiple-exporters/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions apps/multiple-exporters/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
14 changes: 14 additions & 0 deletions apps/multiple-exporters/app/api/service/[slug]/edge/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { runService } from "../../service";

export const runtime = "edge";
export const dynamic = "force-dynamic";

export async function GET(
request: Request,
{ params }: { params: { slug: string } }
) {
const data = await runService(request);
return new Response(`Success edge ${params.slug} ${data}`, {
status: 200,
});
}
13 changes: 13 additions & 0 deletions apps/multiple-exporters/app/api/service/[slug]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { runService } from "../service";

export const dynamic = "force-dynamic";

export async function GET(
request: Request,
{ params }: { params: { slug: string } }
) {
const data = await runService(request);
return new Response(`Success ${params.slug} ${data}`, {
status: 200,
});
}
34 changes: 34 additions & 0 deletions apps/multiple-exporters/app/api/service/service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { trace } from "@opentelemetry/api";

export function runService(request: Request): Promise<string> {
const url = new URL(request.url);
return trace.getTracer("sample").startActiveSpan(
"sample-span",
{
attributes: {
foo: "bar",
},
},
async (span) => {
const dataUrl = url.searchParams.get("dataUrl");
if (!dataUrl) {
span.end();
return "<no data>";
}

const response = await fetch(dataUrl, {
method: "POST",
body: JSON.stringify({ cmd: "echo", data: { foo: "bar" } }),
headers: { "X-Cmd": "echo" },
cache: "no-store",
});
if (dataUrl.includes("example")) {
span.end();
return await response.text();
}
const json = await response.json();
span.end();
return json.foo;
}
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type Props, Component } from "../../../component";

export const runtime = "edge";
export const dynamic = "force-dynamic";

export default function Home(props: Props) {
return <Component {...props} />;
}
7 changes: 7 additions & 0 deletions apps/multiple-exporters/app/behind-middleware/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { type Props, Component } from "../../component";

export const dynamic = "force-dynamic";

export default function Home(props: Props) {
return <Component {...props} />;
}
85 changes: 85 additions & 0 deletions apps/multiple-exporters/app/component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { SpanStatusCode, trace } from "@opentelemetry/api";

export interface Props {
searchParams?: {
dataUrl?: string;
status?: string;
error?: string;
};
}

export async function Component({ searchParams }: Props): Promise<JSX.Element> {
const data = await trace.getTracer("sample").startActiveSpan(
"sample-span",
{
attributes: {
foo: "bar",
},
},
async (span) => {
if (searchParams?.error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: "error from component",
});
span.end();
const error = new Error("error from component");
(error as any).status = 500;
throw error;
}
const dataUrl = searchParams?.dataUrl;
if (!dataUrl) {
span.end();
return null;
}
try {
const response = await fetch(dataUrl, {
method: "POST",
body: JSON.stringify({
cmd: searchParams.status ? "status" : "echo",
data: { status: searchParams.status, foo: "bar" },
}),
cache: "no-store",
headers: { "X-Cmd": "echo" },
opentelemetry: {
attributes: {
custom1: "value1",
},
},
});
const data = await trace
.getTracer("sample")
.startActiveSpan("process-response", async (span2) => {
try {
const isJson = response.headers
.get("content-type")
?.includes("json");
const json = await (isJson ? response.json() : response.text());
await new Promise((resolve) => setTimeout(resolve, 50));
span2.end();
return json;
} catch (e) {
span2.setStatus({
code: SpanStatusCode.ERROR,
message: e instanceof Error ? e.message : String(e),
});
span2.end();
throw e;
}
});
span.end();
return data;
} catch (e) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: e instanceof Error ? e.message : String(e),
});
span.end();
return null;
}
}
);
return (
<main className="p-6">Serverless component: {JSON.stringify(data)}</main>
);
}
Binary file added apps/multiple-exporters/app/favicon.ico
Binary file not shown.
27 changes: 27 additions & 0 deletions apps/multiple-exporters/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}

@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}

body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}
22 changes: 22 additions & 0 deletions apps/multiple-exporters/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import './globals.css'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}

export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
}
5 changes: 5 additions & 0 deletions apps/multiple-exporters/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const dynamic = "force-dynamic";

export default function Page() {
return <div>Root</div>;
}
8 changes: 8 additions & 0 deletions apps/multiple-exporters/app/slugs/[slug]/edge/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { type Props, Component } from "../../../component";

export const runtime = "edge";
export const dynamic = "force-dynamic";

export default function Home(props: Props) {
return <Component {...props} />;
}
16 changes: 16 additions & 0 deletions apps/multiple-exporters/app/slugs/[slug]/error.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"use client";

type AppError = Error & {
status?: string | number;
digest?: string;
};

export default function ErrorPage({ error }: { error: AppError }): JSX.Element {
return (
<main>
<div style={{ color: "red" }}>ERROR: {error.message}</div>
<div>Status: {error.status ?? "n/a"}</div>
<div>Digest: {error.digest ?? "n/a"}</div>
</main>
);
}
7 changes: 7 additions & 0 deletions apps/multiple-exporters/app/slugs/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { type Props, Component } from "../../component";

export const dynamic = "force-dynamic";

export default function Home(props: Props) {
return <Component {...props} />;
}
38 changes: 38 additions & 0 deletions apps/multiple-exporters/instrumentation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { registerOTel, OTLPHttpJsonTraceExporter, OTLPHttpProtoTraceExporter } from "@vercel/otel";
import {
BatchSpanProcessor
} from "@opentelemetry/sdk-trace-base";

export function register() {

registerOTel({
serviceName: "sample-app",
spanProcessors: [
// Exports to Vercel OTEL collector
'auto',
// Exports to Axiom
new BatchSpanProcessor(new OTLPHttpJsonTraceExporter({ url: 'https://api.axiom.co/v1/traces', headers: {
'Authorization': `Bearer ${process.env.AXIOM_API_TOKEN}`, // Replace $API_TOKEN with your actual API token
'X-Axiom-Dataset': process.env.AXIOM_DATASET // Replace $DATASET with your dataset
} })),
// Exports to Checkly
new BatchSpanProcessor(new OTLPHttpProtoTraceExporter({ url: "https://otel.eu-west-1.checklyhq.com", headers: { 'authorization': process.env.CHECKLY_API_TOKEN } })),
],
instrumentationConfig: {
fetch: {
ignoreUrls: [/^https:\/\/telemetry.nextjs.org/],
propagateContextUrls: [/^http:\/\/localhost:\d+/],
dontPropagateContextUrls: [/no-propagation\=1/],
attributesFromRequestHeaders: {
"request.cmd": "X-Cmd",
},
attributesFromResponseHeaders: {
"response.server": "X-Server",
},
},
},
attributesFromHeaders: {
client: "X-Client",
},
});
}
Loading

0 comments on commit faeb349

Please sign in to comment.