{"name":"@whatwg-node/server","version":"0.9.2","author":{"name":"Arda TANRIKULU","email":"ardatanrikulu@gmail.com"},"license":"MIT","_id":"@whatwg-node/server@0.9.2","homepage":"https://github.com/ardatan/whatwg-node#readme","bugs":{"url":"https://github.com/ardatan/whatwg-node/issues"},"dist":{"shasum":"5684f89681cb3b145987da670d2e67448e47214e","tarball":"http://registry-npm.ywwl.com/@whatwg-node/server/download/@whatwg-node/server-0.9.2.tgz","fileCount":35,"integrity":"sha512-W8CzF9Lvu/AKE+HFmKmTwJZ91G+zPmn0zjsl47hjcY5y0/kZqkCqwB86c0y8rRf8+bV5hJ2ChDK8otN0y6fzng==","signatures":[{"sig":"MEUCIQCEf1mwWO2/P1iK3yCcnIT0i8qlCpqpQAjX13aiji5LbAIgAJLg0CV8UWd22D2KwvwdCelO/E2aOOz9h3BNP5jXLnc=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":86307,"size":15475,"noattachment":false,"key":"/@whatwg-node/server/-/@whatwg-node/server-0.9.2.tgz"},"main":"cjs/index.js","type":"module","module":"esm/index.js","engines":{"node":">=16.0.0"},"exports":{".":{"import":{"types":"./typings/index.d.ts","default":"./esm/index.js"},"default":{"types":"./typings/index.d.ts","default":"./esm/index.js"},"require":{"types":"./typings/index.d.cts","default":"./cjs/index.js"}},"./package.json":"./package.json"},"gitHead":"3bc2e6f3bbe978a7ccea23f5c50b100c6f6b2d34","typings":"typings/index.d.ts","_npmUser":{"name":"ardatan","email":"ardatanrikulu@gmail.com"},"repository":{"url":"git+https://github.com/ardatan/whatwg-node.git","type":"git","directory":"packages/server"},"typescript":{"definition":"typings/index.d.ts"},"_npmVersion":"9.5.1","description":"Fetch API compliant HTTP Server adapter","directories":{},"sideEffects":false,"_nodeVersion":"18.16.1","dependencies":{"tslib":"^2.3.1","@whatwg-node/fetch":"^0.9.7"},"_hasShrinkwrap":false,"_npmOperationalInternal":{"tmp":"tmp/server_0.9.2_1688318295836_0.24040423209030837","host":"s3://npm-registry-packages"},"readme":"# WHATWG Node Generic Server Adapter\n\n`@whatwg-node/server` helps you to create a generic server implementation by using WHATWG Fetch API\nfor Node.js, AWS Lambda, Cloudflare Workers, Deno, Express, Fastify, Koa, Next.js and Sveltekit.\n\nOnce you create an adapter with `createServerAdapter`, you don't need to install any other platform\nspecific package since the generic adapter will handle it automatically.\n\n## How to start\n\nLet's create a basic Hello World server adapter.\n\n```ts\n// myServerAdapter.ts\nimport { createServerAdapter } from '@whatwg-node/server'\n\nexport default createServerAdapter((request: Request) => {\n  return new Response(`Hello World!`, { status: 200 })\n})\n```\n\n## Integrations\n\nYou can use your server adapter with the following integrations:\n\n### Node.js\n\n[Node.js](https://nodejs.org/api/http.html) is the most popular server side JavaScript runtime.\n\n```ts\nimport { createServer } from 'http'\nimport myServerAdapter from './myServerAdapter'\n\n// You can create your Node server instance by using our adapter\nconst nodeServer = createServer(myServerAdapter)\n// Then start listening on some port\nnodeServer.listen(4000)\n```\n\n### AWS Lambda\n\nAWS Lambda is a serverless computing platform that makes it easy to build applications that run on\nthe AWS cloud. Our adaoter is platform agnostic so they can fit together easily. In order to reduce\nthe boilerplate we prefer to use\n[Serverless Express from Vendia](https://github.com/vendia/serverless-express).\n\n```ts\nimport { APIGatewayEvent, APIGatewayProxyResult, Context } from 'aws-lambda'\nimport type { Handler } from '@aws-cdk/aws-lambda'\nimport myServerAdapter from './myServerAdapter'\n\ninterface ServerContext {\n  event: APIGatewayEvent\n  lambdaContext: Context\n}\n\nexport async function handler(\n  event: APIGatewayEvent,\n  lambdaContext: Context\n): Promise<APIGatewayProxyResult> {\n  const url = new URL(event.path, 'http://localhost')\n  if (event.queryStringParameters != null) {\n    for (const name in event.queryStringParameters) {\n      const value = event.queryStringParameters[name]\n      if (value != null) {\n        url.searchParams.set(name, value)\n      }\n    }\n  }\n\n  const response = await myServerAdapter.fetch(\n    url,\n    {\n      // For v1.0 you should use event.httpMethod\n      method: event.requestContext.http.method,\n      headers: event.headers as HeadersInit,\n      body: event.body\n        ? Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')\n        : undefined\n    },\n    {\n      event,\n      lambdaContext\n    }\n  )\n\n  const responseHeaders: Record<string, string> = {}\n\n  response.headers.forEach((value, name) => {\n    responseHeaders[name] = value\n  })\n\n  return {\n    statusCode: response.status,\n    headers: responseHeaders,\n    body: await response.text(),\n    isBase64Encoded: false\n  }\n}\n```\n\n### Cloudflare Workers\n\nCloudflare Workers provides a serverless execution environment that allows you to create entirely\nnew applications or augment existing ones without configuring or maintaining infrastructure. It uses\nFetch API already so we can use our adapter as an event listener like below;\n\n```ts\nimport myServerAdapter from './myServerAdapter'\n\nself.addEventListener('fetch', myServerAdapter)\n```\n\n### Deno\n\n[Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust](https://deno.land/).\nYou can use our adapter as a Deno request handler like below;\n\n```ts\nimport myServerAdapter from './myServerAdapter.ts'\n\nDeno.serve(myServerAdapter)\n```\n\n### Express\n\n[Express is the most popular web framework for Node.js.](https://expressjs.com/) It is a minimalist\nframework that provides a robust set of features to handle HTTP on Node.js applications.\n\nYou can easily integrate your adapter into your Express application with a few lines of code.\n\n```ts\nimport express from 'express'\nimport myServerAdapter from './myServerAdapter'\n\nconst app = express()\n\n// Bind our adapter to `/mypath` endpoint\napp.use('/mypath', myServerAdapter)\n\napp.listen(4000, () => {\n  console.log('Running the server at http://localhost:4000/mypath')\n})\n```\n\n### Fastify\n\n[Fastify is one of the popular HTTP server frameworks for Node.js.](https://www.fastify.io/). You\ncan use your adapter easily with Fastify.\n\nSo you can benefit from the powerful plugins of Fastify ecosystem.\n[See the ecosystem](https://www.fastify.io/docs/latest/Guides/Ecosystem/)\n\n```ts\nimport fastify, { FastifyReply, FastifyRequest } from 'fastify'\nimport myServerAdapter from './myServerAdapter'\n\n// This is the fastify instance you have created\nconst app = fastify({ logger: true })\n\n/**\n * We pass the incoming HTTP request to our adapter\n * and handle the response using Fastify's `reply` API\n * Learn more about `reply` https://www.fastify.io/docs/latest/Reply/\n **/\napp.route({\n  url: '/mypath',\n  method: ['GET', 'POST', 'OPTIONS'],\n  handler: async (req, reply) => {\n    const response = await myServerAdapter.handleNodeRequestAndResponse(req, reply, {\n      req,\n      reply\n    })\n    response.headers.forEach((value, key) => {\n      reply.header(key, value)\n    })\n\n    reply.status(response.status)\n\n    // Fastify doesn't accept `null` as a response body\n    reply.send(response.body || undefined)\n\n    return reply\n  }\n})\n\napp.listen(4000)\n```\n\n### Koa\n\n[Koa is another Node.js server framework designed by the team behind Express, which aims to be a smaller, more expressive.](https://koajs.com/)\nYou can add your adapter to your Koa application with a few lines of code then\n[benefit middlewares written for Koa.](https://github.com/koajs/koa/wiki)\n\n```ts\nimport Koa from 'koa'\nimport myServerAdapter from './myServerAdapter'\n\nconst app = new Koa()\n\napp.use(async ctx => {\n  const response = await myServerAdapter.handleNodeRequest(ctx.req)\n\n  // Set status code\n  ctx.status = response.status\n\n  // Set headers\n  response.headers.forEach((value, key) => {\n    ctx.append(key, value)\n  })\n\n  ctx.body = response.body\n})\n\napp.listen(4000, () => {\n  console.log('Running the server at http://localhost:4000')\n})\n```\n\n### Next.js\n\n[Next.js](https://nextjs.org/) is a web framework that allows you to build websites very quickly and\nour new server adapter can be integrated with Next.js easily as an API Route.\n\n```ts\n// pages/api/myEndpoint.ts\n// Next.js API route support: https://nextjs.org/docs/api-routes/introduction\nimport type { NextApiRequest, NextApiResponse } from 'next'\nimport myServerAdapter from './myServerAdapter'\n\nexport const config = {\n  api: {\n    // Disable body parsing if you expect a request other than JSON\n    bodyParser: false\n  }\n}\n\nexport default myServerAdapter\n```\n\n### SvelteKit\n\n[SvelteKit](https://kit.svelte.dev/) is the fastest way to build svelte apps. It is very simple, and\nlet you build frontend & backend in a single place\n\n```ts\nimport myServerAdapter from './myServerAdapter'\n\nexport { myServerAdapter as get, myServerAdapter as post }\n```\n\n### Bun\n\n[Bun](https://bun.sh/) is a modern JavaScript runtime like Node or Deno, and it supports Fetch API\nas a first class citizen. So the configuration is really simple like any other JS runtime;\n\n```ts\nimport myServerAdapter from './myServerAdapter'\n\nBun.serve(myServerAdapter)\n\nconst server = Bun.serve(yoga)\n\nconsole.info(`Server is running on ${server.hostname}`)\n```\n\n## File Uploads / Multipart Requests\n\nMultipart requests are a type of HTTP request that allows you to send blobs together with regular\ntext data which has a mime-type `multipart/form-data`.\n\nFor example, if you send a multipart request from a browser with `FormData`, you can get the same\n`FormData` object in your request handler.\n\n```ts\nimport { createServerAdapter } from '@whatwg-node/server'\n\nconst myServerAdapter = createServerAdapter(async request => {\n  // Parse the request as `FormData`\n  const formData = await request.formData()\n  // Select the file\n  const file = formData.get('file')\n  // Process it as a string\n  const fileTextContent = await file.text()\n  // Select the other text parameter\n  const regularTextData = formData.get('additionalStuff')\n  // ...\n  return Response.json({ message: 'ok' })\n})\n```\n\nYou can learn more about [File API](https://developer.mozilla.org/en-US/docs/Web/API/File) on MDN\ndocumentation.\n\n## Routing and Middlewares\n\nWe'd recommend to use `fets` to handle routing and middleware approach. It uses\n`@whatwg-node/server` under the hood.\n\n> Learn more about `fets` [here](https://github.com/ardatan/fets)\n","publish_time":1688318296008,"maintainers":[{"name":"ardatan","email":"ardatanrikulu@gmail.com"}],"_cnpm_publish_time":1688318296008,"dist-tags":{"alpha":"0.13.3-alpha-20261110014155-22adefff4a6cdea2621e4b6f9cfa78e634349591","latest":"0.13.3","rc":"0.13.1-rc-20261016084928-37b9c99ead24898b1677924f2ac0e2537e42734d"}}