Skip to content

Commit

Permalink
docs: add example with Next.js (with pages router)
Browse files Browse the repository at this point in the history
  • Loading branch information
darrachequesne committed Mar 25, 2024
1 parent 5017681 commit b0568b2
Show file tree
Hide file tree
Showing 33 changed files with 1,154 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Expand Up @@ -55,6 +55,8 @@ jobs:
- webpack-build-server
- basic-crud-application/angular-client
- basic-crud-application/vue-client
- nextjs-pages-router-api-route
- nextjs-pages-router-custom-server

steps:
- name: Checkout repository
Expand Down
36 changes: 36 additions & 0 deletions examples/nextjs-pages-router-api-route/.gitignore
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
40 changes: 40 additions & 0 deletions examples/nextjs-pages-router-api-route/README.md
@@ -0,0 +1,40 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.js`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
7 changes: 7 additions & 0 deletions examples/nextjs-pages-router-api-route/jsconfig.json
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
6 changes: 6 additions & 0 deletions examples/nextjs-pages-router-api-route/next.config.mjs
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
};

export default nextConfig;
18 changes: 18 additions & 0 deletions examples/nextjs-pages-router-api-route/package.json
@@ -0,0 +1,18 @@
{
"name": "nextjs-pages-router-api-route",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "14.1.4",
"react": "^18",
"react-dom": "^18",
"socket.io": "^4.7.5",
"socket.io-client": "^4.7.5"
}
}
Binary file not shown.
1 change: 1 addition & 0 deletions examples/nextjs-pages-router-api-route/public/next.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions examples/nextjs-pages-router-api-route/public/vercel.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions examples/nextjs-pages-router-api-route/src/pages/_app.js
@@ -0,0 +1,5 @@
import "@/styles/globals.css";

export default function App({ Component, pageProps }) {
return <Component {...pageProps} />;
}
13 changes: 13 additions & 0 deletions examples/nextjs-pages-router-api-route/src/pages/_document.js
@@ -0,0 +1,13 @@
import { Html, Head, Main, NextScript } from "next/document";

export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
5 changes: 5 additions & 0 deletions examples/nextjs-pages-router-api-route/src/pages/api/hello.js
@@ -0,0 +1,5 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction

export default function handler(req, res) {
res.status(200).json({ name: "John Doe" });
}
45 changes: 45 additions & 0 deletions examples/nextjs-pages-router-api-route/src/pages/api/socket.io.js
@@ -0,0 +1,45 @@
import { Server } from "socket.io";
import { Server as Engine } from "engine.io";

const engine = new Engine({
pingInterval: 2000
});

const io = new Server();

io.bind(engine);

io.on("connection", (socket) => {
// ...
});

let once = true;

export default function handler(req, res) {
if (once) {
once = false;
const server = req.socket.server;

// the default listener closes the websocket connection if the path does not match "/_next/webpack-hmr"
// see https://github.com/vercel/next.js/blob/f9d73cc2fa710a7ba90ee28f7783a8f05ea62b3a/packages/next/src/server/lib/router-server.ts#L669-L671
const defaultListener = server.listeners("upgrade")[0];
server.removeAllListeners("upgrade");

server.on("upgrade", (req, socket, head) => {
if (req.url.startsWith("/api/socket.io")) {
engine.handleUpgrade(req, socket, head);
} else {
defaultListener.call(server, req, socket, head);
}
});
}

engine.handleRequest(req, res);
}

export const config = {
api: {
bodyParser: false, // prevents body parsing
externalResolver: true, // prevents "this may result in stalled requests" warnings
},
}
56 changes: 56 additions & 0 deletions examples/nextjs-pages-router-api-route/src/pages/index.js
@@ -0,0 +1,56 @@
import Head from "next/head";
import Image from "next/image";
import { Inter } from "next/font/google";
import styles from "@/styles/Home.module.css";
import { useEffect, useState } from "react";
import { socket } from "@/socket";

const inter = Inter({ subsets: ["latin"] });

export default function Home() {
const [isConnected, setIsConnected] = useState(false);
const [transport, setTransport] = useState("N/A");

useEffect(() => {
if (socket.connected) {
onConnect();
}

function onConnect() {
setIsConnected(true);
setTransport(socket.io.engine.transport.name || "N/A");

socket.io.engine.on("upgrade", (transport) => {
setTransport(transport.name);
});
}

function onDisconnect() {
setIsConnected(false);
setTransport("N/A")
}

socket.on("connect", onConnect);
socket.on("disconnect", onDisconnect);

return () => {
socket.off("connect", onConnect);
socket.off("disconnect", onDisconnect);
};
}, []);

return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div>
<p>Status: { isConnected ? "connected" : "disconnected" }</p>
<p>Transport: { transport }</p>
</div>
</>
);
}
9 changes: 9 additions & 0 deletions examples/nextjs-pages-router-api-route/src/socket.js
@@ -0,0 +1,9 @@
import { io } from "socket.io-client";

const isBrowser = typeof window !== "undefined";

// only create the Socket.IO client on the client side (no ssr)
export const socket = isBrowser ? io({
path: "/api/socket.io",
addTrailingSlash: false,
}) : {};

0 comments on commit b0568b2

Please sign in to comment.