Giter Site home page Giter Site logo

fastify-nextjs's Introduction

@fastify/nextjs

CI NPM version js-standard-style

React server-side rendering support for Fastify with Next.js framework. This library is for letting an existing Fastify server utilize NextJS, not for replacing NextJS' internal webserver with Fastify.

Install

npm i @fastify/nextjs next react react-dom

Usage

Since Next.js needs some time to be ready on the first launch, you must declare your routes inside the after callback, after you registered the plugin. The plugin will expose the next API in Fastify that will handle the rendering for you.

const fastify = require('fastify')()

fastify
  .register(require('@fastify/nextjs'))
  .after(() => {
    fastify.next('/hello')
  })

fastify.listen({ port: 3000 }, err => {
  if (err) throw err
  console.log('Server listening on http://localhost:3000')
})

All your server rendered pages must be saved in the folder pages, as you can see in the Next.js documentation.

// /pages/hello.js
export default () => <div>hello world</div>

If you need to pass custom options to next just pass them to register as second parameter.

fastify.register(require('@fastify/nextjs'), { dev: true })

If you need to handle the render part yourself, just pass a callback to next:

fastify.next('/hello', (app, req, reply) => {
  // your code
  // `app` is the Next instance
  app.render(req.raw, reply.raw, '/hello', req.query, {})
})

If you need to render with Next.js from within a custom handler, use reply.nextRender

app.setErrorHandler((err, req, reply) => {
  return reply.nextRender('/a')
})

If you need to render a Next.js error page, use reply.nextRenderError

app.setErrorHandler((err, req, reply) => {
  return reply.status(err.statusCode || 500).nextRenderError(err)
})

If you need to handle HEAD routes, you can define the HTTP method:

fastify.next('/api/*', { method: 'GET' });
fastify.next('/api/*', { method: 'HEAD' });

Assets serving

By default plugin handle route ${basePath}/_next/* and forward to Next.js.

If you have custom preprocessing for _next/* requests, you can prevent this this handling with noServeAssets: true property for plugin options:

fastify
  .register(require('@fastify/nextjs'), {
    noServeAssets: true
  })
  .after(() => {
    fastify.next(`${process.env.BASE_PATH || ''}/_next/*`, (app, req, reply) => {
      // your code
      app.getRequestHandler()(req.raw, reply.raw).then(() => {
        reply.hijack()
      })
    })
  })

under-pressure

The plugin includes under-pressure, which can be configured by providing an underPressure property to the plugin options.

Using under-pressure allows implementing a circuit breaker that returns an error when the health metrics are not respected. Because React server side rendering is a blocking operation for the Node.js server, returning an error to the client allows signalling that the server is under too much load.

The available options are the same as those accepted by under-pressure.

For example:

fastify.register(require('@fastify/nextjs'), {
  underPressure: {
    exposeStatusRoute: true
  }
})
  • underPressure - bool|object

    • (default) when false, under-pressure is not registered
    • when true, under-pressure is registered with default options
    • when it is an object, under-pressure is registered with the provided options

Custom properties on the request object

If you want to share custom objects (for example other fastify plugin instances - e.g. @fastify/redis) across the server/client with each page request, you can use the onRequest hook to add it to the request object. Here is an example on how to do it:

const Fastify = require('fastify')
const FastifyRedis = require('@fastify/redis')
const FastifyNextJS = require('@fastify/nextjs')

const fastify = Fastify()
fastify.register(FastifyRedis, { host: '127.0.0.1' })
fastify.register(FastifyNextJS)

fastify.register(function(instance) {
  // for performance reasons we do not want it to run on every request
  // only the nextjs one should run
  instance.addHook('onRequest', function(request, reply, done) {
    // define a custom property on the request
    request.raw.customProperty = { hello: "world" }
    // OR make the instance of @fastify/redis available in the request
    request.raw.redisInstance = instance.redis
    done()
  })

  instance.next('/', function(app, request, reply) {
    // your custom property containing the object will be available here
    // request.raw.customProperty
    // OR the redis instance
    // request.raw.redisInstance
    app.render(request.raw, reply.raw, '/hello', request.query, {})
  })
}, { prefix: '/hello' })

In the example above we made the customProperty and redisInstance accessible in every request that is made to the server. On the client side it can be accessed like in this example:

const CustomPropPage = ({ cp, ri }) => <div>custom property value: {cp} | redis instance: {ri}</div>;

export default CustomPropPage;

export const getServerSideProps = async function (ctx) {
  return {
    props: {
      cp: ctx.req.customProperty,
      ri: ctx.req.redisInstance,
    }
  };
};

Plugin Timeout and Next.js development mode

The default timeout for plugins in Fastify is 10000ms, which can be a problem for huge Next.js Projects where the initial build time is higher than that. Usually, you will get an error like this:

Error: ERR_AVVIO_PLUGIN_TIMEOUT: plugin did not start in time: /app/node_modules/@fastify/nextjs/index.js. You may have forgotten to call 'done' function or to resolve a Promise

The workaround or fix is to increase the plugin timeout:

const isDev = process.env.NODE_ENV !== 'production';
const fastify = Fastify({ pluginTimeout: isDev ? 120_000 : undefined });

Development

CI currently runs npm@6 so when upgrading packages, please use this version.

Acknowledgements

This project is kindly sponsored by:

License

Licensed under MIT.

fastify-nextjs's People

Contributors

awwong1 avatar cemremengu avatar daopk avatar darkgl0w avatar delvedor avatar dependabot-preview[bot] avatar dependabot[bot] avatar drakhart avatar eomm avatar ethan-arrowood avatar fdawgs avatar franky47 avatar github-actions[bot] avatar greenkeeper[bot] avatar jetsly avatar jimmiehansson avatar jsumners avatar koderfunk avatar lependu avatar mcollina avatar millette avatar neophob avatar pabloszx avatar radomird avatar salmanm avatar simenb avatar simoneb avatar stefee avatar uzlopak avatar zekth avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastify-nextjs's Issues

Ready callback borken

If you use the second example

fastify.ready(() => {
  fastify.next('/index')
})

then this error is thrown

new Error('root plugin has already booted')

Add option to set Cache Duration for _next files

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

It would be awesome if we could set a custom cache duration for the files under the _next path. It seems to be 1d per default, but I haven't found any solution to increase this.

Motivation

Since Next.JS adds content hashes into the name, it would be great if we can increase the cache duration to improve the page performance.

Example

No response

Add type declaration file

Nice library! It would be nice to see this with TypeScript support. Is this something you would accept a PR for?

How to use opts? Confused about next: property

I saw that when defining a route, you can pass custom options to restrict the "method" and "schema" which are explained in the Fastify docs, but there is another required option, "next", that I do not understand:

next(
path: string,
opts:
| {
method: HTTPMethod;
schema: RouteSchema;
next: UrlLike;
}
| FastifyNextCallback,
handle?: FastifyNextCallback
): void;

According to the definition, it is supposed to a URL object, but I have no idea what this value should be or why it is required?

For example:

const schema = {querystring: {name: {type: "string"}}};
server.next("/hello/:name", {method: "GET", schema, next: ?????}, (next, req, reply) => {
    return next.render(req.raw, reply.res, "/hello", {name: req.params.name});
});

start failed after add tailwind

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

3.6.0

Plugin version

3.0.0

Node.js version

14.17.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.4

Description

after add tailwind to css file,
the npm run dev start failed

image

Steps to Reproduce

i created repository https://github.com/Raz-Tw/fastify-nextjs

the last commit

Expected Behavior

normally start into dev mode

Assignment for options misplaced in plugin (Next.js 7.0.3)

Description
The current state of implementation of constructing the options object for Next to read on its construct is passed incorrectly.

  const app = Next(Object.assign(
    { dev: process.env.NODE_ENV !== 'production' },
    options
  ))

Environment
fastify 1.13.3
fastify-nextjs 4.0.0
next 7.0.3

Effect
The Next construct is not aware of the current environment state, getting locked into development mode.

Resolution
Construct object by returning chain in right order

const app = Next(Object.assign({}, options, { dev: process.env.NODE_ENV !== 'production' }))

None of my functions are working

Out of the box, does Fastify support using ES6?

I've got a fastify app serving up a Next.js document, but none of my onClick functions are working, and neither are my lifecycle methods.

An in-range update of standard is breaking the build 🚨


☝️ Important announcement: Greenkeeper will be saying goodbye πŸ‘‹ and passing the torch to Snyk on June 3rd, 2020! Find out how to migrate to Snyk and more at greenkeeper.io


The devDependency standard was updated from 14.3.1 to 14.3.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

standard is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 26 commits.

  • 558df00 14.3.2
  • a8e318e Add changelog entry for 14.3.2
  • 133a4c9 Merge pull request #1492 from standard/eslint68
  • a2df23b Upgrade ESLint to 6.8.x
  • fb7e2a3 remove sponsor
  • ecda198 Update README.md
  • 4bc1671 Update README.md
  • e514626 add sponsor
  • 2b86c68 spacing
  • a702d2e Reposition CodeFund sponsorship link (#1446)
  • a28b5d0 Reposition CodeFund sponsorship link
  • 0f86fb9 Merge pull request #1445 from ZY2071/master
  • b4726d7 perf: Change the examples for rule 'No octal literals' .
  • 4bdaa2f perf: make the rule 'No octal literals' more specific.
  • f5d758e Update README-ja.md for d901c54 (#1435)

There are 26 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Can't set options.dev = false programmatically

πŸ› Bug Report

Can't set dev option to false programmatically, option redeclared with Object.assign to true. dev option can be changed only with NODE_ENV = production

To Reproduce

Steps to reproduce the behavior:

fastify.register(fastifyNext, { dev: false }).after(() => {
    server.next('/');
  });

Next.js started in development mode.

https://runkit.com/alekzonder/object-assign

Expected behavior

When dev option set to false, Next.js should be started in production mode without rebuilding pages on fly

Your Environment

  • node version: 12.16.3
  • fastify version: =3.1.1
  • os: Mac

I fix this with swapping Object.assign arguments

`fastify.next is not a function` when running `NODE_ENV=production`

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

3.20.2

Plugin version

6.0.0

Node.js version

16.6.2

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

20.04.2

Description

Exactly similar to this #88 (comment)

    fastify.next('/hello')
            ^

TypeError: fastify.next is not a function

occurs if my NODE_ENV is set to production. Changing increasing the pluginTimeout doesn't fix it. Setting my NODE_ENV to development does.

Steps to Reproduce

  1. Setup the basic fastify-nextjs example found in the readme
  2. Run with NODE_ENV set to production
  3. Issue occurs

Expected Behavior

No response

Run fastify-nextjs in a subsite plugin aftter a prefix

πŸš€ Feature Proposal

I will use an example to explain the feature proposal:

  1. let's say user visit site-nextjs.abc.com/hello
  2. It is rewritten to abc.com/site-nextjs/hello, which is handled by a plugin with a prefix site-nextjs
  3. Fastify-next is registerred at the subserver of the plugin handling prefix site-nextjs, not at the global fastify server
  4. fasitfy-next renderr nextjs as it is top level nextjs app
  5. nextjs is installed at a subfolder for example sites/site-nextjs

I have tested with current version of fastify-next and found out nextjs always looks for pages at project root, even though it is installed at subfolders.

Motivation

Support multiple sites with different nextjs instances for testing and development.
I don't know if it is able to set nextjs root directory. If yes, it would be a pretty easy job now.

Example

Multiple nextjs development project running on the same server and possibly with other sub-sites running other engines.

Promise may not be fulfilled with 'undefined' when statusCode is not 204

Example is working , but i got this warning in console output:
{"level":50,"time":1545106522717,"msg":"Promise may not be fulfilled with 'undefined' when statusCode is not 204","pid":13839,"hostname":"DESKTOP-SAF118C","reqId":2,"err":{"type":"Error","message":"Promise may not be fulfilled with 'undefined' when statusCode is not 204","stack":"Error: Promise may not be fulfilled with 'undefined' when statusCode is not 204\n at /mnt/c/sources/fastify/node_modules/fastify/lib/wrapThenable.js:18:34\n at process._tickCallback (internal/process/next_tick.js:68:7)"},"v":1}

And i tried example from nextjs repo : https://github.com/zeit/next.js/tree/canary/examples/custom-server-fastify. Everything is good.

it seems the problem at reply.sent = true.

Fastify hooks on the route opts type

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

πŸš€ Feature Proposal

This would allow to simplify the custom request properties example on the readme https://github.com/fastify/fastify-nextjs#custom-properties-on-the-request-object

Instead of needing a register with a prefix, you could add the hook on the .next call directly.

fastify.next('/hello', {
  onRequest: function (request, reply, done) {
    // define a custom property on the request
    request.raw.customProperty = { hello: "world" }
    // OR make the instance of fastify-redis available in the request
    request.raw.redisInstance = instance.redis
    done()
  }
});

Motivation

Currently it is not possible (as far as I can tell?) to apply a hook to the routes handled by the next plugin only, unless there is a route prefix like in the readme example.

Example

fastify.next('*', {
  {
    onRequest: () => {
      // hook contents here
    },
  },
});

An in-range update of next is breaking the build 🚨

Version 6.1.2 of next was just published.

Branch Build failing 🚨
Dependency next
Current Version 6.1.1
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

next is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes 6.1.2

This release is geared towards supporting styled-components v4.

Patches

  • Update hoist-non-react-statics: #5116

Credits

Huge thanks to @probablyup for helping!

Commits

The new version differs by 3 commits.

  • 932e72b 6.1.2
  • 33692a5 update hoist-non-react-statics (#5116)
  • 0fa642a Update with-hashed-statics example (#5100)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

TypeScript error

πŸ› Bug Report

It is clear that that are types for fastify-nextjs and from what I can tell the types look ok with a 'next' method being applied to fastify. The problem is that it is not being applied properly in my relatively simple application.

To Reproduce

Steps to reproduce the behavior:

import fastify, { RequestGenericInterface } from "fastify";
import fastifyNext from 'fastify-nextjs';

const app = fastify({ logger: true })
    .register(fastifyNext)
    .after(() => {
        fastify.next('/hello')
    });

Expected behavior

I expect there not to be a typescript error that says

Property 'next' does not exist on type '{ <Server extends Http2SecureServer, Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>, Reply extends RawReplyDefaultExpression<...> = RawReplyDefaultExpression<...>, Logger extends FastifyLoggerInstance = FastifyLoggerInstance>(opts: FastifyHttp2SecureOptions<...>): FastifyIn...'.ts(2339)

Your Environment

  • node version: 12
  • fastify version: >=2.0.0
  • os: Mac
  • ts-node

TypeError: fastify.next is not a function

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.22.0

Plugin version

6.0.0

Node.js version

14.15.1

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

10.15.7

Description

I found that the plugin was not executed after preparation.

app.prepare().then(()=>{
// Not performed
})

Steps to Reproduce

package.json

"scripts": {
    "dev": "node server.js",
    "build": "next build",
    "start": "NODE_ENV=production node server.js",
    "lint": "next lint"
  },
"dependencies": {
    "fastify": "^3.22.0",
    "fastify-mongodb": "^4.1.1",
    "fastify-nextjs": "^6.0.0",
    "fastify-static": "^4.4.2",
    "next": "11.1.2",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },

server.js

const fastify = require('fastify')();
const fastifyNextjs = require('fastify-nextjs');
const dev = process.env.NODE_ENV !== 'production';
const customOption = {dev};
fastify.register(fastifyNextjs,customOption).after(()=>{
    console.log(fastify);
    fastify.next('/test');
});
fastify.listen(3000,'0.0.0.0',(err, address) => {
    if(err){
        throw err;
    };
    console.log(`Server listening on ${address}`);
});

bash

yarn run dev

TypeError: fastify.next is not a function

Expected Behavior

No response

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.12.0 to 16.13.0.
  • The devDependency react-dom was updated from 16.12.0 to 16.13.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for 16.13.0 (February 26, 2020)

React

  • Warn when a string ref is used in a manner that's not amenable to a future codemod (@lunaruan in #17864)
  • Deprecate React.createFactory() (@trueadm in #17878)

React DOM

Concurrent Mode (Experimental)

Artifacts

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

`req` object in `getServerSideProps` is not updating whenever the page is revisited

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

I'm using fastify-nextjs and here is my server.js:

const fastify = require('fastify')()
const fastifyCookie = require('fastify-cookie')
const fastifyServerSession = require('fastify-server-session')

fastify.register(fastifyCookie);

fastify
  .register(require('fastify-nextjs'))
  .after(() => {
	fastify.next('/', (app, req, reply) => {
		app.render(req.raw, reply.raw, '/', req.query);
	})
  })

fastify.listen(3000, err => {
  if (err) throw err
  console.log('Server listening on http://localhost:3000')
})

I also have an API route init:

exports.init = async function (request, reply) {
	try {
		const date = new Date();
		const nextMonthDate = date.setDate(date.getDate() + 30);

		reply.setCookie('hello', 'world', { expires: nextMonthDate });

                console.log('cookie in init', request.headers.cookie); // properly always prints 'hello=world; _ga=GA1.1.145480481.1604842511; _ym_uid=1604842511951463416; _ym_d=1604842511'

		return reply.send();
	} catch (err) {
		return reply.code(500).send();
	}
};

In my index page, I have the following content:

import React from 'react';
import { GetServerSideProps } from 'next';

const Index = React.memo(({ Component, ...pageProps }: AppProps) => {
	return <div>{'index page'}</div>;
});

export default Index;

export const getServerSideProps: GetServerSideProps = async (ctx) => {
	const cookies = ctx.req.headers.cookie; // always prints '_ga=GA1.1.145480481.1604842511; _ym_uid=1604842511951463416; _ym_d=1604842511'

        console.log('cookie in getServerSideProps', cookies)

	console.log('cookies', cookies);

	return {
		props: {}
	};
};

setCookies properly sets it, but getServerSideProps never catches it.

What am I doing wrong here?

Unable to read Body of POST

πŸ› Bug Report

Body is never presented in context.req

To Reproduce

  1. Create POST page.
  2. Send POST request to this page
  3. Render the data in body
export async function getServerSideProps(context) {
    let body = ''
    let req = context.req
   console.log(context.req)

    req.on('data', chunk => {
        console.log('1')
    })
    req.on('readable', function() {
        console.log('2')
    })
    req.on('end', function() {
        console.log('3')
    })

    return {
        props: {payment: body}
    }
}

Expected behavior

context.req.body is not null

Your Environment

  • node version: v12.3.1
  • fastify version: >=^2.0.0
  • os: Mac

404 on fastify.next("/")

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

3.18.0

Plugin version

5.4.1

Node.js version

v12.22.1

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 20.04

Description

Whenever i'm trying to run fastify.next("/") i'm getting a 404 on the page.

app.ts file:

import fastify from "fastify";
import fastifyNext from "fastify-nextjs";

const app = fastify({ logger: true, pluginTimeout: 60000 });

app.register(fastifyNext).after(() => {
  app.next("/");
  app.next("/game");
});

app.listen(3000, err => {
  if (err) throw err;
  console.log("Server listening on http://localhost:3000");
});

./pages/_app.tsx:

import "./global.css";
import React from "react";
import { HomeContainer } from "./_app.styled";

const Home = () => {
  return <HomeContainer>Item!</HomeContainer>;
};

export default Home;

Steps to Reproduce

error stack:

{"level":30,"time":1624403145677,"pid":15293,"hostname":"localhost","reqId":"req-h","req":{"method":"GET","url":"/_next/webpack-hmr?page=/_error","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57010},"msg":"incoming request"}
{"level":30,"time":1624403146493,"pid":15293,"hostname":"localhost","reqId":"req-h","res":{"statusCode":200},"responseTime":815.8709299564362,"msg":"request completed"}
{"level":30,"time":1624403146499,"pid":15293,"hostname":"localhost","reqId":"req-i","req":{"method":"GET","url":"/","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57016},"msg":"incoming request"}
{"level":30,"time":1624403146508,"pid":15293,"hostname":"localhost","reqId":"req-i","res":{"statusCode":404},"responseTime":8.826359033584595,"msg":"request completed"}
{"level":30,"time":1624403146569,"pid":15293,"hostname":"localhost","reqId":"req-j","req":{"method":"GET","url":"/_next/static/chunks/webpack.js?ts=1624403146503","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57024},"msg":"incoming request"}
{"level":30,"time":1624403146569,"pid":15293,"hostname":"localhost","reqId":"req-k","req":{"method":"GET","url":"/_next/static/chunks/main.js?ts=1624403146503","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57026},"msg":"incoming request"}
{"level":30,"time":1624403146569,"pid":15293,"hostname":"localhost","reqId":"req-l","req":{"method":"GET","url":"/_next/static/chunks/react-refresh.js?ts=1624403146503","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57028},"msg":"incoming request"}
{"level":30,"time":1624403146575,"pid":15293,"hostname":"localhost","reqId":"req-j","res":{"statusCode":200},"responseTime":5.87729799747467,"msg":"request completed"}
{"level":30,"time":1624403146577,"pid":15293,"hostname":"localhost","reqId":"req-l","res":{"statusCode":200},"responseTime":7.718837022781372,"msg":"request completed"}
{"level":30,"time":1624403146612,"pid":15293,"hostname":"localhost","reqId":"req-m","req":{"method":"GET","url":"/_next/static/chunks/pages/_app.js?ts=1624403146503","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57032},"msg":"incoming request"}
{"level":30,"time":1624403146632,"pid":15293,"hostname":"localhost","reqId":"req-m","res":{"statusCode":200},"responseTime":20.25190806388855,"msg":"request completed"}
{"level":30,"time":1624403146636,"pid":15293,"hostname":"localhost","reqId":"req-n","req":{"method":"GET","url":"/_next/static/chunks/pages/_error.js?ts=1624403146503","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57038},"msg":"incoming request"}
{"level":30,"time":1624403146642,"pid":15293,"hostname":"localhost","reqId":"req-n","res":{"statusCode":200},"responseTime":5.939499020576477,"msg":"request completed"}
{"level":30,"time":1624403146646,"pid":15293,"hostname":"localhost","reqId":"req-o","req":{"method":"GET","url":"/_next/static/development/_ssgManifest.js?ts=1624403146503","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57048},"msg":"incoming request"}
{"level":30,"time":1624403146647,"pid":15293,"hostname":"localhost","reqId":"req-p","req":{"method":"GET","url":"/_next/static/development/_buildManifest.js?ts=1624403146503","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57050},"msg":"incoming request"}
{"level":30,"time":1624403146649,"pid":15293,"hostname":"localhost","reqId":"req-o","res":{"statusCode":200},"responseTime":2.8975419998168945,"msg":"request completed"}
{"level":30,"time":1624403146650,"pid":15293,"hostname":"localhost","reqId":"req-p","res":{"statusCode":200},"responseTime":3.00094997882843,"msg":"request completed"}
{"level":30,"time":1624403146823,"pid":15293,"hostname":"localhost","reqId":"req-k","res":{"statusCode":200},"responseTime":254.14596498012543,"msg":"request completed"}
{"level":30,"time":1624403147368,"pid":15293,"hostname":"localhost","reqId":"req-q","req":{"method":"GET","url":"/_next/static/chunks/node_modules_next_dist_client_dev_noop_js.js","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57056},"msg":"incoming request"}
{"level":30,"time":1624403147370,"pid":15293,"hostname":"localhost","reqId":"req-q","res":{"statusCode":200},"responseTime":1.8548099994659424,"msg":"request completed"}
{"level":30,"time":1624403147416,"pid":15293,"hostname":"localhost","reqId":"req-r","req":{"method":"GET","url":"/_next/webpack-hmr?page=/_error","hostname":"localhost","remoteAddress":"127.0.0.1","remotePort":57060},"msg":"incoming request"}

Expected Behavior

Should hopefully be 200 response, but it responds 404. it should be noted that /game works fine and responds 200 properly.

fastify.next is not a function

You have already researched for similar issues?

Yes. I searched in the issue list and could n't find any.

Are you sure this is an issue with the fastify or are you just looking for some help?

The issue seem to be in fastify-nextjs plugin.

Steps to reproduce.

  1. clone https://github.com/fastify/fastify-nextjs.git
  2. cd fastify-nextjs && npm install
  3. run npm run dev

node version: v12.16.1
npm : 6.13.4

Error:
image

If you have issues with the fastify.io site, please open an issue here.

Rendering ourselves too painful

This syntax really looks painful:

fastify.next('/hello', (app, req, reply) => {
  // your code
  // `app` is the Next instance
  app.render(req.req, reply.res, '/hello', req.query, {}})
})

req.req and reply.res? Ugh ... can we do this more elegantly? Not sure how yet but something like

app.render(req, reply, '/hello', req.query, {}})

and correct/wrap this internally? I don't know. Just a suggestion to make it more attractive and less error prone for new users.

Response header set via `reply.header()` in a custom handler never gets sent

πŸ› Bug Report

A response header that's set via reply.header() or reply.headers() in a custom handler will never be sent.

This is because Fastify buffers headers internally instead of setting them on the http.ServerResponse instance, and only sends them after reply.send() is called. But since Next.js calls .end() directly on the http.ServerResponse instance, Fastify never has an opportunity to set response headers, and the buffered headers never get sent.

One way to address this might be for fastify-nextjs to iterate over Fastify's response headers and call reply.res.setHeader(...) to set each header on the http.ServerResponse before passing control to the custom handler or Next.js. Unfortunately, Fastify doesn't appear to provide any public API to get all the internally buffered headers; the only option is to get an individual header by name via reply.getHeader(), which is insufficient. I'm curious if anyone has ideas.

To Reproduce

Here's a failing test that reproduces this:

test('should serve Fastify response headers set by a custom handler', t => {
  t.plan(3)

  const fastify = Fastify()

  fastify
    .register(require('./index'))
    .after(() => {
      fastify.next('/hello', (app, req, reply) => {
        reply.header('test-header', 'hello');
        app.render(req.req, reply.res, '/hello', req.query, {})
      })
    })

  fastify.inject({
    url: '/hello',
    method: 'GET'
  }, (err, res) => {
    t.error(err)
    t.equal(res.statusCode, 200)
    t.equal(res.headers['test-header'], 'hello')
  })

  fastify.close()
});

Expected behavior

The response served by Next.js should include headers set by Fastify, and the test above should pass.

Your Environment

  • node version: 12.15.0
  • fastify version: 2.12.1
  • os: Mac, Linux

Next.js API routes support?

πŸ› Bug Report

We're not able to render next.js api routes, as described here: https://nextjs.org/docs/api-routes/introduction

To Reproduce

Steps to reproduce the behavior:

// pages/api/example.js

export default (req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify({ test: true }))
}
// server.js

const path = require('path')
const nextConfig = require.resolve('./next.config')

const fastify = require('fastify')({
  logger: true,
  ignoreTrailingSlash: true,
})

fastify
  .register(require('fastify-cookie'))
  .register(require('fastify-nextjs'), { dev: false, dir: __dirname, conf: nextConfig })
  .register(require('fastify-static'), {
    root: path.join(__dirname, 'public'),

    maxAge: '365d',
    immutable: true,
    cacheControl: true,
  })
  .after(() => {
    fastify.next('/api/*')
  })
// next.config.js
const withImages = require('next-images')

module.exports = withImages({
  assetPrefix: '',
  webpack(config, options) {
    return config
  }
})
{"level":30,"time":1591260316508,"pid":65946,"hostname":"dev001","reqId":1,"req":{"method":"GET","url":"/api/example","hostname":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":53206},"msg":"incoming request","v":1}
Could not find files for /api/example in .next/build-manifest.json
TypeError: res.setHeader is not a function
    at module.exports.6Rh6.__webpack_exports__.default (/Users/dev001/workspace/app/.next/server/static/AE6ko8zfA0RfswT5Q88B0/pages/api/maintenance.js:115:7)
    at d (/Users/dev001/workspace/app/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:498)
    at Za (/Users/dev001/workspace/app/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:39:16)
    at a.b.render (/Users/dev001/workspace/app/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:44:476)
    at a.b.read (/Users/dev001/workspace/app/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:44:18)
    at renderToString (/Users/dev001/workspace/app/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:54:364)
    at render (/Users/dev001/workspace/app/node_modules/next/dist/next-server/server/render.js:82:16)
    at Object.renderPage (/Users/dev001/workspace/app/node_modules/next/dist/next-server/server/render.js:323:20)
    at /Users/dev001/workspace/app/.next/server/static/AE6ko8zfA0RfswT5Q88B0/pages/_document.js:2369:21
    at Generator.next (<anonymous>)
{"level":30,"time":1591260316585,"pid":65946,"hostname":"dev001","reqId":1,"res":{"statusCode":500},"responseTime":75.81719696521759,"msg":"request completed","v":1}

Expected behavior

API routes should return valid json.

Your Environment

  • node version: 12
  • fastify version: 2.11.0
  • os: Mac

Workaround

Define API routes in fastify, but it would be preferred if we could do it in next.js.

Redis instance is being mapped only once per app visit and only to the page that is being hit

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Reproducible demo/repo here

I am mapping my redis instance to req.raw, but for some reason, it doesn't persist through page navigations, even if you return to the same page.

In my afterHandler, I'm doing the following:

fastify.next('/', (app, req, reply) => {
	req.raw.redisInstance = fastify.redis;
	app.render(req.raw, reply.raw, '/', req.query);
});

fastify.next('/another', (app, req, reply) => {
	req.raw.redisInstance = fastify.redis;
	app.render(req.raw, reply.raw, '/another', req.query);
});

If you visit the index file or the another route, then the redis instance will be available the first time. The redis instance is also available if you refresh the page.

However if you first first index, then go to another, and then go back to index, the reference to the redis instance is lost.

I've tried doing as was suggested here, but to no avail.

What am I doing wrong here?

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.6.1 to 16.6.2.
  • The devDependency react-dom was updated from 16.6.1 to 16.6.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of fastify is breaking the build 🚨

The devDependency fastify was updated from 1.13.0 to 1.13.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v1.13.1
  • chore: pin ajv to 6.5.5 - #1282
Commits

The new version differs by 10 commits.

  • bb2e65e Bumped v1.13.1
  • 7e27787 chore: pin ajv to 6.5.5 (#1282)
  • ec4f0a1 Add listen notice for GCP (#1264)
  • e901ff5 add fastify-cloudevents to Community plugins (#1248)
  • a952698 fix(package): update tiny-lru to version 2.0.0 (#1260)
  • 01ef79b Fix typo in README (#1257)
  • c53174c Set up CI with Azure Pipelines (#1226)
  • 584bc28 doc(decorators): fix markdown style (#1247)
  • 8cbc78a chore(package): update eslint-plugin-typescript to version 0.13.0 (#1243)
  • 7e18ab4 Bump typescript-eslint-parser (#1242)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Rename to fastify-nextjs

Hey!

I know, there is already an issue #29 but still, the package/repository should be named as fastify-next or fastify-nextjs (i prefer the @tsnieman name) because:

  • The package/repository integrates only with Next.Js.
  • The package/repository does not integrate with barebone React environments.
  • The package/repository name barely says that is about React, not Nextjs which is misleading.
  • The current package/repository name could be used to provide an real integration with barebone react environments which have nothing with Next.JS to do.

Regards,
TheAifam5

Outputs 404 each time

Outputs 404 each time. how to cancel.

[2018-03-23T10:31:31.952Z] INFO (7400 on USERCHI-NBKB0FN): incoming request
reqId: 17
req: {
"id": 17,
"method": "GET",
"url": "/_next/-/main.js",
"remoteAddress": "127.0.0.1",
"remotePort": 52960
}
[2018-03-23T10:31:31.955Z] INFO (7400 on USERCHI-NBKB0FN): Not found
reqId: 17
res: {
"statusCode": 404
}
err: {
"type": "Error",
"message": "Not found",
"stack":
Error: Not found
at Context.basic404 [as handler] (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\fastify.js:679:26)
at preHandlerCallback (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\lib\handleRequest.js:88:30)
at handler (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\lib\handleRequest.js:72:5)
at handleRequest (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\lib\handleRequest.js:22:5)
at onRunMiddlewares (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\fastify.js:346:5)
at middlewareCallback (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\fastify.js:334:7)
at Object.routeHandler [as handler] (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\fastify.js:224:7)
at Router.lookup (G:\codes\mycode\shuoyan\vmxue
ode_modules\_find-my-way@1.11.1@find-my-way\index.js:269:17)
at Router.defaultRoute (G:\codes\mycode\shuoyan\vmxue
ode_modules\_fastify@1.1.1@fastify\fastify.js:675:16)
at Router._defaultRoute (G:\codes\mycode\shuoyan\vmxue
ode_modules\_find-my-way@1.11.1@find-my-way\index.js:415:10)
at Router.lookup (G:\codes\mycode\shuoyan\vmxue
ode_modules\_find-my-way@1.11.1@find-my-way\index.js:268:36)
at emitTwo (events.js:126:13)
at Server.emit (events.js:214:7)
at parserOnIncoming (_http_server.js:602:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:116:23)
}
[2018-03-23T10:31:31.958Z] INFO (7400 on USERCHI-NBKB0FN): request completed
reqId: 17
res: {
"statusCode": 404
}
responseTime: 6.0355259999632835

Disposing inactive page(s): /home

An in-range update of fastify is breaking the build 🚨

The devDependency fastify was updated from 2.11.0 to 2.12.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v2.12.0

πŸ“š PR:

  • fix: skip serialization for json string (#1937)
  • Added fastify-casl to Community Plugins (#1977)
  • feature: added validation context to validation result (#1915)
  • ESM support (#1984)
  • fix: adjust hooks body null (#1991)
  • Added mcollina's plugin "fastify-secure-session" (#1999)
  • Add fastify-typeorm-plugin to community plugins (#1998)
  • Remove Azure Pipelines (#1985)
  • Update validation docs (#1994)
  • Drop Windows-latest and Node 6 from CI as its failing. (#2002)
  • doc: fix esm-support anchor (#2001)
  • Docs(Fluent-Schema.md): fix fluent schema repo link (#2007)
  • fix - docs - hooks - error handling (#2000)
  • add fastify-explorer to ecosystem (#2003)
  • Add a recommendations doc (#1997)
  • Fix TOC typo in recommendations (#2009)
  • docs(Typescript): typo (#2016)
  • docs: fix onResponse parameter (#2020)
  • Update template bug.md (#2025)
  • fix replace way enum (#2026)
  • docs: update inject features (#2029)
  • Update Copyright Year to 2020 (#2031)
  • add generic to typescript Reply.send payload (#2032)
  • Shorten longest line (docs) (#2035)
  • docs: OpenJS CoC (#2033)
  • Workaround for using one schema for multiple routes (#2044)
  • docs: inject chainable methods (#1917) (#2043)
  • http2: handle graceful close (#2050)
  • chore(package): update fluent-schema to version 0.10.0 (#2057)
  • chore(package): update yup to version 0.28.1 (#2059)
  • Update README.md (#2064)
  • Added fastify-response-validation to ecosystem (#2063)
  • fix: use opts of onRoute hook (#2060)
  • Fixed documentation typo (#2067)
  • Add missing TS definition for ServerOptions.genReqId function arg (#2076)
  • fix: throw hooks promise rejection (#2070) (#2074)
  • Add docs to stop processing hooks with async (#2079)
Commits

The new version differs by 38 commits.

  • 7a37924 Bumped v2.12.0
  • aacefcd Add docs to stop processing hooks with async (#2079)
  • c052c21 fix: throw hooks promise rejection (#2070) (#2074)
  • 6b39870 Add missing TS definition for ServerOptions.genReqId function arg (#2076)
  • 7fa4bdd Fixed documentation typo (#2067)
  • 6b73e0a fix: use opts of onRoute hook (#2060)
  • 7bb9733 Added fastify-response-validation to ecosystem (#2063)
  • 0a1c1f0 Update README.md (#2064)
  • bd9f608 chore(package): update yup to version 0.28.1 (#2059)
  • e19d078 chore(package): update fluent-schema to version 0.10.0 (#2057)
  • d0c976e http2: handle graceful close (#2050)
  • af8a6ac docs: inject chainable methods (#1917) (#2043)
  • 62f21b1 Workaround for using one schema for multiple routes (#2044)
  • 5258f42 docs: OpenJS CoC (#2033)
  • ac46905 Shorten longest line (docs) (#2035)

There are 38 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Missing deps - react-dom/server - document issue

πŸ’₯ Regression Report

I installed the module, registered it to my fastify server - then starting of my service failed due missing deps.

As written in the readme, I ran npm i fastify-nextjs next --save to install this module, package.json diff looked fine:

  • "fastify-nextjs": "^5.1.0",
  • "next": "^10.0.7",

however I tried to start my server which failed:

Error: Cannot find module 'react'
Require stack:
- /project/node_modules/next/dist/next-server/server/render.js
- /project/node_modules/next/dist/next-server/server/next-server.js
- /project/node_modules/next/dist/server/next.js
- /project/node_modules/fastify-nextjs/index.js
- /project/src/lib/rest.js
- /project/src/index.js
Error: Cannot find module 'react-dom/server'
Require stack:
...

So I started to install npm install react --save, npm install react-dom/server --save... but this failed with

npm install react-dom/server --save                                  Mi 17 Feb 12:45:35 2021
npm ERR! Can't install github:react-dom/server#9c6de716d028f17736d0892d8a3d8f3ac2cb62bd: Missing package name

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/bar/.npm/_logs/2021-02-17T12_48_12_329Z-debug.log

is the manual react and react-dom/server step really needed or just a "following error" of the react-dom/server issue?

Last working version

As I followed the readme I assume this worked some time ago...

To Reproduce

Steps to reproduce the behavior:

npm i
npm install react-dom/server --save

Expected behavior

all dependencies are working ;)

Your Environment

  • node version: 14.15.4
  • fastify version: 3.11.0
  • os: Mac
{
  "name": "foo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": "14.x"
  },
  "scripts": {
    "format": "npm run lint -- --fix",
    "lint": "eslint --ext js,json .",
    "test": "jest",
    "start": "node src/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-sdk": "^2.839.0",
    "debug": "^4.3.1",
    "dotenv": "^8.2.0",
    "fastify": "^3.11.0",
    "fastify-cookie": "^5.1.0",
    "fastify-jwt": "^2.3.0",
    "fastify-nextjs": "^5.1.0",
    "http-errors": "^1.8.0",
    "next": "^10.0.7",
    "node-schedule": "^2.0.0",
    "pg": "^8.5.1",
    "react": "^17.0.1",
    "simple-event-statistics": "github:neophob/simple-statistics"
  },
  "devDependencies": {
    "eslint": "^7.19.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jest": "^24.1.3",
    "eslint-plugin-json": "^2.1.2",
    "eslint-plugin-react": "^7.22.0",
    "jest": "^26.6.3",
    "node-fetch": "^2.6.1"
  }
}

Using fastify-nextjs with fastify-cookie

Hi, i have module fastify-cookie and fastify-nextjs. I need support cookies for context next pages. Is that possible without parsing cookies again in next request?

export default class Main extends React.Component {
  static async getInitialProps(context) {
    const main =  await fetch.get('/api/main')
    return {main}
  }
  render() {
    <div>{this.props.main}</div>
  }
}

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.6.9 to 12.7.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

failure to set up when using fastify-cli boilerplate

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Could you please add to the documentation what needs to be done in order to use fastify-nextjs with fastify-cli generated boilerplate project structure? Any attempt to use fastify-cli with fastify-nextjs results in failure to run the server.

An in-range update of fastify-plugin is breaking the build 🚨

The dependency fastify-plugin was updated from 1.6.0 to 1.6.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

fastify-plugin is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v1.6.1

πŸ“š PR:

  • chore(package): update standard to version 13.0.1
  • chore(package): update standard to version 14.0.0
  • fix linting errors for standard@14
  • Updated deps
  • Update standard to the latest version πŸš€ (#74)
  • Error name (#84)
Commits

The new version differs by 7 commits.

  • b9a7ede Bumped v1.6.1
  • df58357 Updated deps
  • 03cdeee Error name (#84)
  • 7d78d57 fix linting errors for standard@14
  • 3686925 chore(package): update standard to version 14.0.0
  • 3d3ca8c Update standard to the latest version πŸš€ (#74)
  • 5204636 chore(package): update standard to version 13.0.1

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Support for use Next-Routes

πŸš€ Feature Proposal

The idea is to implement next-routes within fastify-nextjs to support custom routes when useFileSystemPublicRoutes: false on next.config.js .

Lets take a look on simple custom server for NextJS with next-routes.

// server.js
const { createServer } = require('http')
const next = require('next')
const routes = require('./routes');

const app = next({ dev: true });
const handle = routes.getRequestHandler(app);

app.prepare().then(() => {
  createServer((req, res) => {
      handle(req, res)
  }).listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
// next.config.js
module.exports = {
  useFileSystemPublicRoutes: false,
}
// routes.js
const Routes = require('next-routes');

module.exports = new Routes()
  .add({ name: 'Home', pattern: '/', page: 'Home' })
  .add({ name: 'Product', pattern: '/:slug*/p', page: 'Product' })

Motivation

On my work we need to set the option useFileSystemPublicRoutes as false. We don't want to adopt the Next route pattern in directories for organizational reasons and URL pattern issues.

Example

// server.js
const fastify = require('fastify')()
const routes = require('./routes.js')

fastify
  .register(require('fastify-nextjs'), { dev: true, routes })
  .after(() => {
    fastify.next('/*')
  })

fastify.listen(3000, err => {
  if (err) throw err
  console.log('Server listening on http://localhost:3000')
})

Next.js 11

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure it has not already been reported

Fastify version

3.18.0

Plugin version

5.4.1

Node.js version

14.7.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

NixOS

Description

❯ npm install                    
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! Found: [email protected]
npm ERR! node_modules/next
npm ERR!   next@"11.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer next@"9.x.x || 10.x.x" from [email protected]
npm ERR! node_modules/fastify-nextjs
npm ERR!   fastify-nextjs@"5.4.1" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

Steps to Reproduce

  1. update next to 11.0.0 in package.json
  2. npm install

Expected Behavior

No error and no regressions.

Integration with next-auth fails, routing issue

πŸ› Bug Report

I want to integrate next-auth with my fastify-nextjs project. This worked until the next.auth library does the login/POST callback - somehow this call does not succeed and just times out. I ported the exact same code to a vanilla Next.js project (using npx create-next-app) and there it works flawlessly!

To Reproduce

Expected behavior

call is terminated correct / callback is called. I quickly added some console log into the plugin to figure out where the code hangs:

    function handler (req, reply) {
      if (callback) {
        return callback(app, req, reply)
      }
      console.log("handle next request", req.params)
      return handleNextRequests(req.raw, reply.raw)
        .then(() => {
          console.log("...handled")
          reply.sent = true
        })
  • when the login POST request is hanging, the handleNextRequests function is running
  • when I cancel the POST request (using postman), then the ...handled console output is visible...

the console shows this output:

{"level":30,"time":1613721952594,"pid":94353,"hostname":"hostname","reqId":29,"req":{"method":"POST","url":"/api/auth/callback/credentials","hostname":"localhost:3333","remoteAddress":"::1","remotePort":55873},"msg":"incoming request"}
handle next request { '*': 'auth/callback/credentials' }
event - build page: /api/auth/[...nextauth]
wait  - compiling...
event - compiled successfully

To summarize, I think the POST call to /api/auth/callback/credentials is either not routed correctly OR the return value is invalid (promise vs. value maybe?)

Your Environment

  • node version: 12 and 14
  • fastify version: 3.12
  • os: Mac

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.16 to 12.12.17.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.12.0 to 12.12.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Rename to fastify-next

Because it's not really about React but next.js. There is no direct dependency to React

Unable to render _error page, renders 404 page instead

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

3.25.0

Plugin version

7.0.0

Node.js version

16.13.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

11.6.1

Description

The plugin uses app.render under the hood, which explicitly disallows rendering _app, _document and _error pages:

https://github.com/vercel/next.js/blob/e75361fd03872b097e817634c049b3185f24cf56/packages/next/server/base-server.ts#L1704

Attempting to render the _error path (as described in the readme) results in a 404 Not Found response.

If you need to render with Next.js from within a custom handler (such as an error handler), use reply.nextRender

app.setErrorHandler((err, req, reply) => {
  reply.status(err.statusCode || 500)
  return reply.nextRender('/_error')
})

Steps to Reproduce

See description.

Expected Behavior

The plugin should either:

  1. Decorate the request with the app instance, so that app.renderError can be called manually
  2. Decorate fastify with a reply.nextRenderError which proxies the app.renderError similar to how reply.nextRender works

Enums do not match in url path

I'm trying to match url paths with specific locale enums.
I configured the rule in this way

fastify
  .register(require('fastify-nextjs'))
  .after(() => {
    fastify.next('/:lang(en|it)', (app, req, reply) => {
      app.render(req.raw, reply.res, `/`, req.params)
    })
  })

The path matches successfully the espected urls:

  • /en
  • /it

but it matches also

  • /cannotenter
  • /itdoesntwork

Am I not setting the rule in the appropriate way?

It takes 10s to restart hello world app.

I know this is not fastify's problem but I think we can't use nextjs while developing backend code.
We need 1 way to reload server code but not to restart fastify server.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.