Design Converter
Education
Last updated on Jan 21, 2025
Last updated on Dec 4, 2024
Software Development Executive - II
Next.js is a popular React framework that simplifies building server-side rendered applications. However, there are scenarios where the built-in server doesn't meet your needs. That's where creating a Next.js custom server with TypeScript comes in handy. Whether you're adding middleware, handling custom routes, or integrating third-party services, a custom server provides flexibility and control.
This blog walks you through the process of setting up a custom server using TypeScript, ensuring a smooth development experience and compatibility with production environments.
By default, Next.js serves pages efficiently with its built-in functionality. However, there are scenarios where a custom server is beneficial:
• Adding custom middlewares
• Handling APIs or routes outside Next.js's built-in capabilities
• Performing custom authentication
• Supporting features not covered by the default server
Before diving into the implementation, ensure the following tools and knowledge are in place:
Node.js installed on your machine
Familiarity with TypeScript and JavaScript
A basic understanding of Next.js
First, you'll need to initialize a Next.js project. If you haven't already:
1npx create-next-app@latest --typescript custom-server-example 2cd custom-server-example
This creates a TypeScript-ready Next.js project.
To set up a custom server, you'll need Express.js as the core server framework. Install it and other required dependencies:
1npm install express 2npm install --save-dev @types/express
This ensures TypeScript understands the types used in your server code.
Next, define your server entry point. In the root of your project, create a file named server.ts. This will act as the starting point for your custom server.
1import express, { Request, Response } from "express"; 2import { createServer } from "http"; 3import next from "next"; 4 5const dev = process.env.NODE_ENV !== "production"; 6const app = next({ dev }); 7const handle = app.getRequestHandler(); 8 9const server = express(); 10 11app.prepare().then(() => { 12 server.all("*", (req: Request, res: Response) => { 13 return handle(req, res); 14 }); 15 16 const httpServer = createServer(server); 17 httpServer.listen(3000, () => { 18 console.log("Custom server listening on http://localhost:3000"); 19 }); 20});
• We import express and http to build a robust server.
• The next function initializes the Next.js application.
• The handle function processes all requests through Next.js.
Update your scripts to include a command for starting the custom server. In package.json, modify the scripts section:
1"scripts": { 2 "dev": "ts-node server.ts", 3 "build": "next build", 4 "start": "NODE_ENV=production node server.js" 5}
Here, the dev script runs the ts-node server, enabling TypeScript support.
For production, you need to compile your TypeScript code to JavaScript. Update your tsconfig.json to include the following:
1{ 2 "compilerOptions": { 3 "outDir": "./dist", 4 "module": "commonjs", 5 "target": "es6", 6 "strict": true 7 }, 8 "include": ["server.ts"] 9}
Run:
1npx tsc
This generates compiled JavaScript files in the dist directory.
To ensure your custom server is robust, include error handling. Wrap your server initialization in a try-catch block to capture potential errors.
1try { 2 app.prepare().then(() => { 3 server.all("*", (req, res) => handle(req, res)); 4 httpServer.listen(3000, () => console.log("Server running...")); 5 }); 6} catch (error) { 7 console.error("Error starting server:", error); 8}
This ensures any unexpected errors during the server startup are logged and addressed.
Start the server in development mode:
1npm run dev
Visit http://localhost:3000 to see your application running on the custom server.
For production, use the following steps:
1npm run build
1npm run start
TypeScript Errors: Ensure your tsconfig.json is properly configured to recognize all server-related types.
Deployment Issues: Always test your server code locally before deploying to a production environment.
Runtime Errors: Use console.log for debugging during the development phase and ensure your server has comprehensive error handling.
Building a Next.js custom server with TypeScript offers unparalleled flexibility for your applications. By following this guide, you can integrate custom middlewares, manage APIs, and tailor your server to meet specific requirements.
Whether you're running in development or production, this setup ensures a seamless experience for both the client side and the backend. With TypeScript ensuring type safety and ts-node streamlining development, you're equipped to handle any challenge that arises.
Start building your custom server today and take control of your application's server-side capabilities!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.