├── .dockerignore ├── .gitignore ├── Dockerfile ├── README.md ├── app ├── favicon.ico ├── globals.css ├── layout.tsx └── page.tsx ├── docker-entrypoint.js ├── eslint.config.mjs ├── fly.toml ├── next.config.ts ├── package-lock.json ├── package.json ├── postcss.config.mjs ├── public ├── file.svg ├── globe.svg ├── next.svg ├── vercel.svg └── window.svg ├── server.ts ├── tailwind.config.ts └── tsconfig.json /.dockerignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.* 7 | .yarn/* 8 | !.yarn/patches 9 | !.yarn/plugins 10 | !.yarn/releases 11 | !.yarn/versions 12 | 13 | # testing 14 | /coverage 15 | 16 | # next.js 17 | /.next/ 18 | /out/ 19 | 20 | # production 21 | /build 22 | 23 | # misc 24 | .DS_Store 25 | *.pem 26 | 27 | # debug 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | .pnpm-debug.log* 32 | 33 | # env files (can opt-in for committing if needed) 34 | .env* 35 | 36 | # vercel 37 | .vercel 38 | 39 | # typescript 40 | *.tsbuildinfo 41 | next-env.d.ts 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.* 7 | .yarn/* 8 | !.yarn/patches 9 | !.yarn/plugins 10 | !.yarn/releases 11 | !.yarn/versions 12 | 13 | # testing 14 | /coverage 15 | 16 | # next.js 17 | /.next/ 18 | /out/ 19 | 20 | # production 21 | /build 22 | 23 | # misc 24 | .DS_Store 25 | *.pem 26 | 27 | # debug 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | .pnpm-debug.log* 32 | 33 | # env files (can opt-in for committing if needed) 34 | .env* 35 | 36 | # vercel 37 | .vercel 38 | 39 | # typescript 40 | *.tsbuildinfo 41 | next-env.d.ts 42 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax = docker/dockerfile:1 2 | 3 | # Adjust NODE_VERSION as desired 4 | ARG NODE_VERSION=23.7.0 5 | FROM node:${NODE_VERSION}-slim AS base 6 | 7 | LABEL fly_launch_runtime="Next.js" 8 | 9 | # Next.js app lives here 10 | WORKDIR /app 11 | 12 | # Set production environment 13 | ENV NODE_ENV="production" 14 | 15 | 16 | # Throw-away build stage to reduce size of final image 17 | FROM base AS build 18 | 19 | # Install packages needed to build node modules 20 | RUN apt-get update -qq && \ 21 | apt-get install --no-install-recommends -y build-essential node-gyp pkg-config python-is-python3 22 | 23 | # Install node modules 24 | COPY package-lock.json package.json ./ 25 | RUN npm ci --include=dev 26 | 27 | # Copy application code 28 | COPY . . 29 | 30 | # Build application 31 | RUN npx next build --experimental-build-mode compile 32 | 33 | # Remove development dependencies 34 | RUN npm prune --omit=dev 35 | 36 | 37 | # Final stage for app image 38 | FROM base 39 | 40 | # Copy built application 41 | COPY --from=build /app /app 42 | 43 | # Entrypoint sets up the container. 44 | ENTRYPOINT [ "/app/docker-entrypoint.js" ] 45 | 46 | # Start the server by default, this can be overwritten at runtime 47 | EXPOSE 3000 48 | CMD [ "npm", "run", "start" ] 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sample App: Using web sockets on Next.js 2 | 3 | This is a very simple chat application that demonstrates how to web sockets with Next.js. See the video for a walk through of this code: https://youtu.be/9DEvkYB5_A4 4 | 5 | ## Running locally 6 | 7 | First install all dependencies: 8 | 9 | ```bash 10 | npm install 11 | ``` 12 | 13 | Then start the development server: 14 | 15 | ```bash 16 | npm run dev 17 | ``` 18 | 19 | ## Deploying to Fly.io 20 | 21 | To deploy this application to Fly.io, simply run: 22 | 23 | ```bash 24 | fly launch 25 | ``` 26 | 27 | When it asks: 28 | ``` 29 | An existing fly.toml file was found for app ws-demo-next 30 | ? Would you like to copy its configuration to the new app? 31 | ``` 32 | 33 | Choose **Yes**. 34 | 35 | When it asks: 36 | ``` 37 | ? Do you want to tweak these settings before proceeding? 38 | ``` 39 | 40 | Choose **No** (unless you want to change the app name or region, etc) 41 | 42 | Once finished, you'll be able to access your app at `https://.fly.dev` -------------------------------------------------------------------------------- /app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fly-apps/nextjs-websockets/f0a2aa5c1abd88af075133259e6a80f854118766/app/favicon.ico -------------------------------------------------------------------------------- /app/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | :root { 6 | --background: #ffffff; 7 | --foreground: #171717; 8 | } 9 | 10 | @media (prefers-color-scheme: dark) { 11 | :root { 12 | --background: #0a0a0a; 13 | --foreground: #ededed; 14 | } 15 | } 16 | 17 | body { 18 | color: var(--foreground); 19 | background: var(--background); 20 | font-family: Arial, Helvetica, sans-serif; 21 | } 22 | -------------------------------------------------------------------------------- /app/layout.tsx: -------------------------------------------------------------------------------- 1 | import type { Metadata } from "next"; 2 | import { Geist, Geist_Mono } from "next/font/google"; 3 | import "./globals.css"; 4 | 5 | const geistSans = Geist({ 6 | variable: "--font-geist-sans", 7 | subsets: ["latin"], 8 | }); 9 | 10 | const geistMono = Geist_Mono({ 11 | variable: "--font-geist-mono", 12 | subsets: ["latin"], 13 | }); 14 | 15 | export const metadata: Metadata = { 16 | title: "Create Next App", 17 | description: "Generated by create next app", 18 | }; 19 | 20 | export default function RootLayout({ 21 | children, 22 | }: Readonly<{ 23 | children: React.ReactNode; 24 | }>) { 25 | return ( 26 | 27 | 30 | {children} 31 | 32 | 33 | ); 34 | } 35 | -------------------------------------------------------------------------------- /app/page.tsx: -------------------------------------------------------------------------------- 1 | "use client" 2 | import { useEffect, useRef, useState } from "react"; 3 | 4 | export default function Home() { 5 | const [messages, setMessages] = useState([]); 6 | const [newMessage, setNewMessage] = useState(''); 7 | const [connectionStatus, setConnectionStatus] = useState<'connected' | 'disconnected' | 'connecting'>('connecting'); 8 | const wsRef = useRef(null); 9 | 10 | useEffect(() => { 11 | 12 | const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; 13 | const ws = new WebSocket(`${protocol}//${window.location.host}/api/ws`); 14 | wsRef.current = ws; 15 | 16 | 17 | ws.onopen = () => { 18 | setConnectionStatus('connected'); 19 | }; 20 | 21 | ws.onclose = () => { 22 | setConnectionStatus('disconnected'); 23 | }; 24 | 25 | ws.onmessage = (event) => { 26 | setMessages((prevMessages) => [...prevMessages, event.data]); 27 | }; 28 | 29 | const pingInterval = setInterval(() => { 30 | if (ws.readyState === WebSocket.OPEN) { 31 | ws.send(`{"event":"ping"}`); 32 | } 33 | }, 29000); 34 | 35 | return () => { 36 | clearInterval(pingInterval); 37 | if (wsRef.current) { 38 | wsRef.current.close(); 39 | } 40 | }; 41 | }, []) 42 | 43 | const sendMessage = (e: React.FormEvent) => { 44 | e.preventDefault(); 45 | if (!newMessage.trim()) return; 46 | 47 | if (wsRef.current?.readyState === WebSocket.OPEN) { 48 | wsRef.current.send(newMessage); 49 | setNewMessage(''); 50 | } 51 | } 52 | 53 | return ( 54 |
55 |
56 |
61 |
62 |
67 | Status: {connectionStatus} 68 |
69 |
70 | 71 |
74 | {messages.map((message, index) => ( 75 |
79 |

{message}

80 |
81 | ))} 82 |
83 | 84 |
88 |
89 | setNewMessage(e.target.value)} 93 | className="flex-1 rounded-lg border border-gray-200 px-4 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all" 94 | placeholder="Type your message..." 95 | /> 96 | 107 |
108 |
109 |
110 |
111 | //
112 | //
Status: {connectionStatus}
113 | 114 | //
115 | // {messages.map((message, index) => ( 116 | //
{message}
117 | // ))} 118 | //
119 | 120 | //
121 | // setNewMessage(e.target.value)} 125 | // placeholder="Type your message..." 126 | // className="border border-gray-400 rounded p-2" 127 | // /> 128 | // 131 | //
132 | //
133 | ); 134 | } 135 | -------------------------------------------------------------------------------- /docker-entrypoint.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { spawn } = require('node:child_process') 4 | 5 | const env = { ...process.env } 6 | 7 | ;(async() => { 8 | // If running the web server then prerender pages 9 | if (process.argv.slice(-3).join(' ') === 'npm run start') { 10 | await exec('npx next build --experimental-build-mode generate') 11 | } 12 | 13 | // launch application 14 | await exec(process.argv.slice(2).join(' ')) 15 | })() 16 | 17 | function exec(command) { 18 | const child = spawn(command, { shell: true, stdio: 'inherit', env }) 19 | return new Promise((resolve, reject) => { 20 | child.on('exit', code => { 21 | if (code === 0) { 22 | resolve() 23 | } else { 24 | reject(new Error(`${command} failed rc=${code}`)) 25 | } 26 | }) 27 | }) 28 | } 29 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import { dirname } from "path"; 2 | import { fileURLToPath } from "url"; 3 | import { FlatCompat } from "@eslint/eslintrc"; 4 | 5 | const __filename = fileURLToPath(import.meta.url); 6 | const __dirname = dirname(__filename); 7 | 8 | const compat = new FlatCompat({ 9 | baseDirectory: __dirname, 10 | }); 11 | 12 | const eslintConfig = [ 13 | ...compat.extends("next/core-web-vitals", "next/typescript"), 14 | ]; 15 | 16 | export default eslintConfig; 17 | -------------------------------------------------------------------------------- /fly.toml: -------------------------------------------------------------------------------- 1 | # fly.toml app configuration file generated for ws-demo-next on 2025-02-19T15:21:49-08:00 2 | # 3 | # See https://fly.io/docs/reference/configuration/ for information about how to use this file. 4 | # 5 | 6 | app = 'ws-demo-next' 7 | primary_region = 'sea' 8 | 9 | [build] 10 | 11 | [http_service] 12 | internal_port = 3000 13 | force_https = true 14 | auto_stop_machines = 'stop' 15 | auto_start_machines = true 16 | min_machines_running = 0 17 | processes = ['app'] 18 | 19 | [[vm]] 20 | memory = '1gb' 21 | cpu_kind = 'shared' 22 | cpus = 1 23 | -------------------------------------------------------------------------------- /next.config.ts: -------------------------------------------------------------------------------- 1 | import type { NextConfig } from "next"; 2 | 3 | const nextConfig: NextConfig = { 4 | /* config options here */ 5 | }; 6 | 7 | export default nextConfig; 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ws-demo-next", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "node server.ts", 7 | "build": "next build", 8 | "start": "NODE_ENV=production node server.ts", 9 | "lint": "next lint" 10 | }, 11 | "dependencies": { 12 | "next": "15.1.6", 13 | "react": "^19.0.0", 14 | "react-dom": "^19.0.0", 15 | "ws": "^8.18.0" 16 | }, 17 | "devDependencies": { 18 | "@eslint/eslintrc": "^3", 19 | "@flydotio/dockerfile": "^0.7.4", 20 | "@types/node": "^20", 21 | "@types/react": "^19", 22 | "@types/react-dom": "^19", 23 | "@types/ws": "^8.5.14", 24 | "eslint": "^9", 25 | "eslint-config-next": "15.1.6", 26 | "postcss": "^8", 27 | "tailwindcss": "^3.4.1", 28 | "typescript": "^5" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /postcss.config.mjs: -------------------------------------------------------------------------------- 1 | /** @type {import('postcss-load-config').Config} */ 2 | const config = { 3 | plugins: { 4 | tailwindcss: {}, 5 | }, 6 | }; 7 | 8 | export default config; 9 | -------------------------------------------------------------------------------- /public/file.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/globe.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/next.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/vercel.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/window.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /server.ts: -------------------------------------------------------------------------------- 1 | import { parse } from 'node:url'; 2 | import { createServer, Server, IncomingMessage, ServerResponse } from 'node:http'; 3 | import next from 'next'; 4 | import { WebSocket, WebSocketServer } from 'ws'; 5 | import { Socket } from 'node:net'; 6 | 7 | const nextApp = next({ dev: process.env.NODE_ENV !== "production" }); 8 | const handle = nextApp.getRequestHandler(); 9 | const clients: Set = new Set(); 10 | 11 | nextApp.prepare().then(() => { 12 | const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => { 13 | handle(req, res, parse(req.url || '', true)); 14 | }); 15 | 16 | const wss = new WebSocketServer({ noServer: true }); 17 | 18 | wss.on('connection', (ws: WebSocket) => { 19 | clients.add(ws); 20 | console.log('New client connected'); 21 | 22 | ws.on('message', (message: Buffer, isBinary: boolean) => { 23 | console.log(`Message received: ${message}`); 24 | clients.forEach(client => { 25 | if (client.readyState === WebSocket.OPEN && (message.toString() !== `{"event":"ping"}`)) { 26 | client.send(message, { binary: isBinary }); 27 | } 28 | }); 29 | }) 30 | 31 | ws.on('close', () => { 32 | clients.delete(ws); 33 | console.log('Client disconnected'); 34 | }); 35 | }) 36 | 37 | server.on("upgrade", (req: IncomingMessage, socket: Socket, head: Buffer) => { 38 | const { pathname } = parse(req.url || "/", true); 39 | 40 | if (pathname === "/_next/webpack-hmr") { 41 | nextApp.getUpgradeHandler()(req, socket, head); 42 | } 43 | 44 | if (pathname === "/api/ws") { 45 | wss.handleUpgrade(req, socket, head, (ws) => { 46 | wss.emit('connection', ws, req); 47 | }); 48 | } 49 | }) 50 | 51 | server.listen(3000); 52 | console.log('Server listening on port 3000'); 53 | }) -------------------------------------------------------------------------------- /tailwind.config.ts: -------------------------------------------------------------------------------- 1 | import type { Config } from "tailwindcss"; 2 | 3 | export default { 4 | content: [ 5 | "./pages/**/*.{js,ts,jsx,tsx,mdx}", 6 | "./components/**/*.{js,ts,jsx,tsx,mdx}", 7 | "./app/**/*.{js,ts,jsx,tsx,mdx}", 8 | ], 9 | theme: { 10 | extend: { 11 | colors: { 12 | background: "var(--background)", 13 | foreground: "var(--foreground)", 14 | }, 15 | }, 16 | }, 17 | plugins: [], 18 | } satisfies Config; 19 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2017", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "noEmit": true, 9 | "esModuleInterop": true, 10 | "module": "esnext", 11 | "moduleResolution": "bundler", 12 | "resolveJsonModule": true, 13 | "isolatedModules": true, 14 | "jsx": "preserve", 15 | "incremental": true, 16 | "plugins": [ 17 | { 18 | "name": "next" 19 | } 20 | ], 21 | "paths": { 22 | "@/*": ["./*"] 23 | } 24 | }, 25 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], 26 | "exclude": ["node_modules"] 27 | } 28 | --------------------------------------------------------------------------------