Next.js+Fastify自定义服务器动态路由加载无限挂起问题
Next.js + Fastify 动态路由无限挂起问题排查与解决
问题场景
开发小型Next.js应用时,采用Fastify搭配@fastify/nextjs插件搭建自定义服务器,静态路由(如/、/test)加载正常,但动态路由[slug]在浏览器中会无限挂起。
相关代码片段
服务器入口 index.ts
// ... Imports above export const PORT = +(process.env.PORT ?? 3000); run(async () => { // Initialize Fastify const app = fastify({ logger: true, pluginTimeout: 20e3 }); // Initialize Apollo const apollo = new ApolloServer({ typeDefs, resolvers, csrfPrevention: true, cache: 'bounded', plugins: [fastifyAppClosePlugin(app), ApolloServerPluginDrainHttpServer({ httpServer: app.server })], }); console.log('Registering Fastify plugins.'); // ... Register helmet, compression, cookie, and session plugins console.log('Registering Fastify Next.js plugin.'); // Make Fastify work with Next.js await app.register(nextJSPlugin, { dev: true }); // Make Fastify serve up all Next.js pages app.next('*'); console.log('Starting Apollo server.'); // Start the Apollo server await apollo.start(); // Make Fastify handle GraphQL requests app.register(apollo.createHandler()); console.log(`Waiting for connection to MongoDB at ${MONGODB_URI}`); await mongoConnection.asPromise(); console.log('Starting the server...'); // Start the Fastify server app.listen({ port: PORT }, () => { console.log(`Server running on port ${PORT}`); console.log(`GraphQL endpoint: ${apollo.graphqlPath}`); }); });
动态路由页面 [slug].tsx
import { GetStaticPaths, GetStaticProps } from 'next'; import React from 'react'; // Configured Apollo client import { client } from '../apollo/client'; import { PAGES } from '../apollo/queries'; import { PageType } from '../server/models/types'; type PageProps = { slug: string; content: string; }; const Slug = ({ slug, content }: PageProps) => { return <div>thank god it loaded</div>; }; export default Slug; export const getStaticPaths: GetStaticPaths = async () => { const { data } = await client.query<{ pages: PageType[] }>({ query: PAGES, }); return { // The routes supported here are defined by the records in the "Pages" collection in my database paths: data.pages.filter(({ slug }) => slug !== '/').map(({ slug }) => ({ params: { slug } })), fallback: false, }; }; export const getStaticProps: GetStaticProps = async ({ params }) => { const { slug } = params as { slug: string }; const { data } = await client.query<{ pages: [PageType] }>({ query: PAGES, variables: { slug, }, }); return { props: data.pages[0], revalidate: 30, }; };
已完成的排查步骤
- 确认GraphQL服务器运行正常,
pages查询在Postman、Insomnia和cURL中均可正常执行; - 反复验证Apollo Client初始化正确,已成功连接GraphQL服务器;
- 检查项目结构是否存在问题,当前项目结构如下:
- index.ts - /server - /config - /schemas - /models - /utils - /pages - _app.tsx - index.ts - [slug].tsx
最终解决方案
经过排查,确定问题根源在于使用ts-node运行项目。
内容的提问来源于stack exchange,提问作者mstephen19
相关产品推荐
相关产品推荐

