Logo

dev-resources.site

for different kinds of informations.

Nextjs custom server with fastify

Published at
6/29/2024
Categories
react
nextjs
fastify
javascript
Author
markuz899
Categories
4 categories in total
react
open
nextjs
open
fastify
open
javascript
open
Author
9 person written this
markuz899
open
Nextjs custom server with fastify

Image description

React server-side rendering support for Fastify with Next.js framework

In this post we will create a custom server to start an app in nextjs with fastify underneath.

Let's create a new app in nextjs with npx

npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

Let's proceed with the installation of the dependencies

npm install fastify @fastify/static fastify-env dotenv
Enter fullscreen mode Exit fullscreen mode

First let's create an .env file at the root

PORT=6100
Enter fullscreen mode Exit fullscreen mode

On the root of the project, so to speak, next to the src folder we are going to create a new folder called server

Inside we create an index.js file
The content will look like this

require("dotenv").config();
const fastify = require("fastify")();
const fastifyStatic = require("@fastify/static");
const path = require("path");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const host = process.env.HOST || "localhost";
const port = parseInt(process.env.PORT || "6100");

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

(async () => {
  try {
    await app.prepare();

    fastify.register(fastifyStatic, {
      root: path.join(__dirname, "..", "public", "static"),
      prefix: "/static/",
    });

    fastify.all("/*", (req, reply) => {
      reply.hijack();
      handle(req.raw, reply.raw)
        .then(() => {
          reply.raw.end();
        })
        .catch((err) => {
          fastify.log.error(err);
          reply.raw.writeHead(500);
          reply.raw.end("Internal Server Error");
        });
    });

    await fastify.listen({ port, host });

    console.log(`Fastify server ready on port: ${port}`);
  } catch (err) {
    console.log(err);
    process.exit(1);
  }
})();
Enter fullscreen mode Exit fullscreen mode

This is the package.json file with the related run and build scripts

{
  "name": "nextjs_fastify",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev-next": "next dev",
    "dev": "node server/index.js",
    "prod": "cross-env NODE_ENV=production node ./server/index.js",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@fastify/static": "^7.0.4",
    "dotenv": "^16.4.5",
    "fastify": "^4.28.1",
    "fastify-env": "^2.2.0",
    "next": "^14.2.4",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "@types/next": "^9.0.0",
    "@types/node": "^20.14.9",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "cross-env": "^7.0.3",
    "typescript": "^5"
  }
}
Enter fullscreen mode Exit fullscreen mode

Now all we have to do is run the desired scripts and that's it

To run the server in dev mode
npm run dev

To run the server in production mode you will first need to create the build version
npm run build

Only after the build has been completed can we launch the server in production mode with
npm run prod

And tadaan we will now have a client in nextjs with fastify under the hood ๐Ÿš€

Thanks for reading

fastify Article's
30 articles in total
Favicon
Understanding CORS and Setting it up with NestJS + Fastify ๐Ÿš€
Favicon
Building a Real-Time Auction Platform: Behind the Scenes
Favicon
Async Local Storage is Here to Help You
Favicon
Master Node.js with the 5th Edition Cookbook
Favicon
Real-time data replication in Postgres and Node.js
Favicon
NestJS vs. Ditsmod: pipe features
Favicon
NodeJS Framework which one is Fast
Favicon
Gerando Documentaรงรฃo de API Automรกtica com Fastify, @fastify/swagger e Zod
Favicon
Fastify v5 vs v4 โ€” vs Encore.ts
Favicon
nestjs vs fastify Battle
Favicon
Speeding Up Your Website Using Fastify and Redis Cache
Favicon
Streaming PostgreSQL data with Fastify
Favicon
Fastify adoption guide: Overview, examples, and alternatives
Favicon
The Essential Do's and Don'ts of Fastify: Unlocking Your API's Potential
Favicon
How to Customize the Fastify Logger
Favicon
Express.js needs a funeral
Favicon
Serve Next.js with Fastify
Favicon
Nextjs custom server with fastify
Favicon
Testing Your API with Fastify and Vitest: A Step-by-Step Guide
Favicon
Introduction to Fastify: A Superior Node.js Framework
Favicon
Fastify Developers: Upgrade Your Logging with This Simple Guide
Favicon
How to create a lan server using Node.js and Fastify.js
Favicon
Criando sua API com Fastify e Prisma
Favicon
DynamoDB Single Table Design
Favicon
Stop exposing your Node.js metrics ๐Ÿ›‘
Favicon
Fastify Meets WireMock: External Service Mocking
Favicon
The Fastify book is out!
Favicon
How to Automatically Consume RESTful APIs in Your Frontend
Favicon
Validate the Fastify input with Joi
Favicon
Starting With Fastify Today

Featured ones: