applicazza / fastify-nextjs

Serve Next.js requests via Fastify

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@applicazza/fastify-nextjs

@applicazza/fastify-nextjs is a plugin for serving Next.js requests via Fastify.

npm codecov

This project is yet to reach stable state. You may help by contributing and testing it.

Why

Original fastify-nextjs doesn't pass response through Fastify's pipeline thus hooks that you may need won't work. This package is using JavaScript's Proxy to intercept calls to NodeJs http.ServerResponse and pass it to Fastify.

Usage

Add dependencies

yarn add @applicazza/fastify-nextjs
yarn add fastify-static

Disable compression in Next.js (next.config.js)

module.exports = {
  compress: false,
};

Default example

import createFastify from 'fastify';
import fastifyNextJs from '@applicazza/fastify-nextjs';

const dev = process.env.NODE_ENV !== 'production';

const fastify = createFastify();

fastify.register(fastifyNextJs, {
    dev,
});

await fastify.after();

fastify.passNextJsRequests();

await fastify.listen(0);

Extended example

import createFastify from 'fastify';
import fastifyNextJs from '@applicazza/fastify-nextjs';

const dev = process.env.NODE_ENV !== 'production';

const fastify = createFastify();

fastify.register(fastifyNextJs, {
    dev,
});

await fastify.after();

fastify.passNextJsDataRequests();
fastify.passNextJsImageRequests();
if (dev) {
    fastify.passNextJsDevRequests();
} else {
    fastify.passNextJsStaticRequests();
}
fastify.passNextJsPageRequests();

await fastify.listen(0);

Plugin accepts following options:

interface FastifyNextJsOptions {
    basePath?: string;
    dev?: boolean;
    dir?: string;
}

Plugin augments fastify instance with following properties and methods:

interface FastifyNextJsDecoratorArguments {
  logLevel?: LogLevel;
}

interface FastifyInstance {
    nextJsProxyRequestHandler: (request: FastifyRequest, reply: FastifyReply) => void;
    nextJsRawRequestHandler: (request: FastifyRequest, reply: FastifyReply) => void;
    nextServer: NextServer;
    passNextJsRequests: (args?: FastifyNextJsDecoratorArguments) => void;
    passNextJsDataRequests: (args?: FastifyNextJsDecoratorArguments) => void;
    passNextJsDevRequests: (args?: FastifyNextJsDecoratorArguments) => void;
    passNextJsImageRequests: (args?: FastifyNextJsDecoratorArguments) => void;
    passNextJsPageRequests: (args?: FastifyNextJsDecoratorArguments) => void;
    passNextJsStaticRequests: (args?: FastifyNextJsDecoratorArguments) => void;
}

Building from source

yarn build

Testing

yarn test

License

Licensed under MIT.

About

Serve Next.js requests via Fastify

License:MIT License


Languages

Language:TypeScript 92.0%Language:JavaScript 8.0%