Serve Your Next.js Blog in the Terminal with proxy.ts
Detect curl and wget with the Next.js 16 proxy.ts file and answer with a plain-text page read from an example.txt file, with optional terminal colours.
Serve Your Next.js Blog in the Terminal with proxy.ts
Run this in a terminal:
curl blog.example.comInstead of a wall of HTML, you get a clean text page made for the terminal. Open the exact same URL in a browser and you get the normal website.
This tutorial shows how that works. We use the Next.js 16 proxy.ts file to look at the User-Agent header of every request and decide what to send back. To keep things simple, the text itself comes from a plain example.txt file, so you do not need a CMS, a database or any posts to follow along.
By the end you will understand:
- How
proxy.tsdetects command-line clients likecurlandwget - How a rewrite serves different content on the same URL
- How a Route Handler can return a text file as
text/plain - Why you need the
Vary: User-Agentheader - How to test it, add colours, and deploy it
How it works
The feature is three small pieces that work together:
curl blog.example.com
|
v
proxy.ts looks at the User-Agent header
|
|-- browser? -> NextResponse.next() -> normal React page
|
'-- curl? -> NextResponse.rewrite() -> /blog.txt
|
v
app/blog.txt/route.ts reads data/example.txt
|
v
text/plain responseThe important idea is the rewrite. A redirect would send the client to a new URL. A rewrite keeps the URL the same (/) but serves the content of another route (/blog.txt). The visitor never notices anything: curl asks for / and receives text.
Prerequisites
You need a Next.js 16 project that uses the App Router. Nothing else is required.
These are the files we will create:
my-app/
โโโ app/
โ โโโ blog.txt/
โ โโโ route.ts <- plain-text endpoint
โโโ data/
โ โโโ example.txt <- the text we serve
โโโ proxy.ts <- detects curl/wgetNote that proxy.ts lives in the project root, next to app and package.json, and not inside app. In Next.js 16 this file replaces the old middleware.ts.
Step 1: Create the example text file
Create a folder data in the project root and add a file example.txt. This is exactly what the terminal visitor will see, so make it look nice. Here is a small example:
โ Example Blog Notes on building things for the web
----------------------------------------------------------
3 posts ยท latest Nov 15, 2026
01 Serve Your Blog in the Terminal with proxy.ts
Nov 15, 2026 ยท 9 min ยท Next.js ยท proxy.ts ยท curl
Detect curl and wget and answer with plain text.
โ https://blog.example.com/blog/terminal-proxy
02 Reverse Proxying Apps with One Nginx Instance
Sep 23, 2026 ยท 8 min ยท Nginx ยท Self-Hosting
Use a single Nginx to proxy several self-hosted apps.
โ https://blog.example.com/blog/nginx-reverse-proxy
03 How to Check Disk Usage on Linux
Aug 14, 2026 ยท 4 min ยท Linux ยท Sysadmin
Find large files and folders with du, df and ncdu.
โ https://blog.example.com/blog/linux-disk-usage
----------------------------------------------------------
web blog.example.com
github github.com/example
rss /feed.xml
A few notes:
- It is plain UTF-8 text. Characters such as
โandโwork fine in modern terminals, as long as we send the rightContent-Typecharset later. - Full URLs. A terminal has no "current page", so relative links would be useless. Terminals automatically detect
https://...and make them clickable. - Keep lines short. Around 60 characters wide fits comfortably in a default terminal window.
- Start and end with an empty line. It gives the output some breathing room above and below.
Step 2: Create the plain-text route
Now we need a URL that returns this file. In the App Router, a folder that contains a route.ts file becomes an endpoint. A folder name may contain a dot, so app/blog.txt/route.ts creates the route /blog.txt.
// app/blog.txt/route.ts
import { readFile } from 'node:fs/promises'
import path from 'node:path'
export async function GET() {
try {
const file = path.join(process.cwd(), 'data', 'example.txt')
const body = await readFile(file, 'utf8')
return new Response(body, {
headers: {
'content-type': 'text/plain; charset=utf-8',
'cache-control': 'public, max-age=60, s-maxage=300',
vary: 'User-Agent',
},
})
} catch {
return new Response('Could not load the terminal view.\n', {
status: 500,
headers: { 'content-type': 'text/plain; charset=utf-8' },
})
}
}Explanation
GETfunction: A Route Handler exports a function named after the HTTP method it handles. Next.js callsGETwhen someone requests/blog.txt.process.cwd(): The folder the app was started from, which is the project root. We build an absolute path to the file withpath.join, so it works no matter which folder the code lives in.readFile(file, 'utf8'): Reads the file and returns its content as a string. Route Handlers run on the server, so using Node'sfsis fine here.new Response(body, { headers }): Returns a standard webResponsewith a string body.content-type: text/plain; charset=utf-8: Tells the client this is text, not HTML. Without the charset, characters likeโandโmay show up garbled.cache-control: public, max-age=60, s-maxage=300: Clients may cache the answer for 60 seconds, and shared caches (a CDN or reverse proxy) for 5 minutes.vary: User-Agent: Tells caches that the answer depends on theUser-Agentheader. We explain why in Step 3.try/catch: If the file is missing or unreadable, the visitor gets a short error message with status500instead of a stack trace.
You can already test this route in a browser at /blog.txt. You will see your text file as plain text. Note that a browser does not care about the User-Agent here, because we are asking for this URL directly.
Step 3: Detect curl and wget with proxy.ts
Now for the heart of the tutorial. Create proxy.ts in the project root.
// proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
// Command-line clients get the plain-text terminal view; browsers get the normal page.
const CLI_AGENT = /^(curl|wget|httpie|libwww-perl|python-requests|go-http-client)/i
export function proxy(request: NextRequest) {
const userAgent = request.headers.get('user-agent') ?? ''
const response = CLI_AGENT.test(userAgent)
? NextResponse.rewrite(
// keep the query string so ?page=2&tag=linux&q=nginx still work
Object.assign(request.nextUrl.clone(), { pathname: '/blog.txt' })
)
: NextResponse.next()
// Same URL, different body: tell caches/CDNs to key on User-Agent
response.headers.append('Vary', 'User-Agent')
return response
}
export const config = {
matcher: ['/', '/blog'],
}Let us go through it piece by piece.
The file and function name
In Next.js 16 the file is called proxy.ts and exports a function named proxy. In earlier versions this was middleware.ts with a function named middleware. Next.js calls the function with a NextRequest for every request that matches the matcher, before any page or route runs.
The User-Agent check
const CLI_AGENT = /^(curl|wget|httpie|libwww-perl|python-requests|go-http-client)/iEvery HTTP client sends a User-Agent header that identifies it. A few examples:
| Client | Typical User-Agent |
|---|---|
| curl | curl/8.7.1 |
| Wget | Wget/1.21.4 |
| HTTPie | HTTPie/3.2.2 |
| Python requests | python-requests/2.32.0 |
Go net/http | Go-http-client/2.0 |
| Chrome | Mozilla/5.0 (Macintosh; ...) Chrome/... |
The regular expression has three parts worth understanding:
^anchors the match to the start of the string. That is deliberate: browsers include a lot of words in their header, and we only want clients whose header begins with one of our names.(a|b|c)matches any one of the listed names./imakes it case-insensitive, socurl,CurlandCURLall match.
To support another client, add its name to the list. For example powershell if some of your readers use Windows:
const CLI_AGENT = /^(curl|wget|httpie|libwww-perl|python-requests|go-http-client|powershell)/iconst userAgent = request.headers.get('user-agent') ?? ''headers.get() returns null when the header is missing, so ?? '' turns it into an empty string. An empty string never matches the regex, so a request without a User-Agent simply gets the normal website.
Rewrite or continue
const response = CLI_AGENT.test(userAgent)
? NextResponse.rewrite(
Object.assign(request.nextUrl.clone(), { pathname: '/blog.txt' })
)
: NextResponse.next()NextResponse.next()means "carry on as normal". The browser gets the regular page.NextResponse.rewrite(url)means "answer this request with the content of another URL". The address stays the same for the client.
A rewrite is what makes this feel like magic. With a redirect, curl would receive a 307 response and, unless you pass -L, would stop there. With a rewrite, curl blog.example.com directly receives the text.
Why nextUrl.clone() and Object.assign?
request.nextUrl is a NextURL object that knows the full URL, including the query string. We want a URL that is identical, except for the path. So:
clone()makes a copy, so we do not change the original request.Object.assign(copy, { pathname: '/blog.txt' })sets thepathnameproperty on the copy.
The query string stays untouched, so curl "blog.example.com/?page=2" is rewritten to /blog.txt?page=2. Our example route ignores query parameters for now, but because they are preserved you can add support later without changing proxy.ts. You could also write the same thing in three lines if you find that easier to read:
const url = request.nextUrl.clone()
url.pathname = '/blog.txt'
return NextResponse.rewrite(url)The Vary header
response.headers.append('Vary', 'User-Agent')This line is easy to forget and causes confusing bugs when you do.
The URL / now returns different content depending on who asks. If a cache (a CDN, Nginx, or the browser's own cache) stores the HTML answer for / and later serves it to a curl user, that user sees HTML. And the other way around: a browser could get the terminal text.
Vary: User-Agent tells caches: "the response depends on the User-Agent header, so keep separate copies per value". We use append rather than set, so we do not overwrite a Vary header that was already added elsewhere, for example for compression. We add it on both branches, because both versions need the rule. The route handler sets vary: User-Agent on its own response too, for the case where someone requests /blog.txt directly.
One caveat: some CDNs ignore Vary for anything other than Accept-Encoding. If you put one in front of your site, create a rule to bypass the cache for /, or you may see the mix-up described above.
The matcher
export const config = {
matcher: ['/', '/blog'],
}Without a matcher, the proxy would run for every request, including every image, script and stylesheet. Here it only runs for the home page / and the blog index /blog.
Also notice that /blog.txt is not in the matcher. That means a browser can open /blog.txt directly to see the raw text, which is handy while developing.
Step 4: Test everything
Start the dev server:
npm run devThe normal request
curl http://localhost:3000You should see the contents of data/example.txt.
Pretend to be a browser
The -A option changes the User-Agent. This should return the HTML of your normal home page:
curl -A "Mozilla/5.0" http://localhost:3000If you see HTML here and text in the previous command, the detection works.
Check the headers
curl -s -D - -o /dev/null http://localhost:3000-D - prints the response headers to the screen and -o /dev/null throws away the body. Look for these lines:
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
vary: User-AgentTest the query string
curl "http://localhost:3000/?page=2"Always put the URL in quotes. Without quotes your shell treats & as "run in the background" and ? as a wildcard. You will see the same text as before for now, but the request did reach /blog.txt?page=2.
Test with wget
wget -qO- http://localhost:3000-q is quiet and -O- writes the response to standard output.
Edit the file
Change a line in data/example.txt, wait a moment (the route is allowed to be cached for a short time) and run curl again. Your change should show up without restarting anything.
Step 5: Add colours (optional)
Terminals understand ANSI escape codes: the escape character (\x1b) followed by [ starts a control sequence. For example, \x1b[38;5;203m switches the text colour to colour 203 of the 256-colour palette, and \x1b[0m resets all styling.
\x1b[38;5;203m red-ish colour (palette colour 203)
\x1b[1m bold
\x1b[0m reset all stylingYou cannot easily type the escape character in a text editor, so we add placeholders to the text file and let a tiny function convert them. Create a helper:
// lib/colorize.ts
const ESC = '\x1b'
const STYLES: Record<string, string> = {
accent: '38;5;203',
title: '1;38;5;253',
meta: '38;5;245',
dim: '38;5;238',
}
// Turns {{accent}}text{{/}} into coloured text
export function colorize(text: string) {
return text
.replace(/\{\{(\w+)\}\}/g, (match, name: string) =>
STYLES[name] ? `${ESC}[${STYLES[name]}m` : match
)
.replaceAll('{{/}}', `${ESC}[0m`)
}Explanation
STYLES: A palette with a name for each purpose. Naming colours by role instead of by number means you can restyle everything by changing one line.- First
replace: Finds every opening tag such as{{accent}}and swaps it for the matching colour code. Unknown names are left untouched. replaceAll('{{/}}', ...): Swaps every closing tag for the reset code. It does not clash with the first replace, because/is not matched by\w.
Now use the placeholders in data/example.txt:
{{accent}}โ{{/}} {{title}}Example Blog{{/}} {{meta}}Notes on building things for the web{{/}}
{{dim}}----------------------------------------------------------{{/}}
{{meta}}3 posts ยท latest Nov 15, 2026{{/}}
{{dim}}01{{/}} {{title}}Serve Your Blog in the Terminal with proxy.ts{{/}}
{{meta}}Nov 15, 2026 ยท 9 min ยท Next.js ยท proxy.ts ยท curl{{/}}
{{accent}}โ{{/}} {{meta}}https://blog.example.com/blog/terminal-proxy{{/}}And call the helper in the route handler:
// app/blog.txt/route.ts
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { colorize } from '@/lib/colorize'
export async function GET() {
try {
const file = path.join(process.cwd(), 'data', 'example.txt')
const body = colorize(await readFile(file, 'utf8'))
return new Response(body, {
headers: {
'content-type': 'text/plain; charset=utf-8',
'cache-control': 'public, max-age=60, s-maxage=300',
vary: 'User-Agent',
},
})
} catch {
return new Response('Could not load the terminal view.\n', {
status: 500,
headers: { 'content-type': 'text/plain; charset=utf-8' },
})
}
}If your project does not have the @/ import alias, use a relative import such as ../../lib/colorize. Run curl again and the output is now in colour.
If the output is longer than your screen, pipe it into less. The -R flag tells less to render the colours instead of showing the codes as text:
curl -s http://localhost:3000 | less -RStep 6: Deploy it behind Nginx
If you self-host, there is usually a reverse proxy in front of Next.js. Nginx forwards the User-Agent header to your app by default, so the detection works out of the box:
server {
listen 80;
server_name blog.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}If you also cache responses in Nginx with proxy_cache, make sure the cache key includes the User-Agent, or the Vary problem from earlier comes back:
proxy_cache_key "$scheme$host$request_uri$http_user_agent";One more deployment tip: the route reads data/example.txt at runtime, so the file must exist next to your app on the server. With a normal next build and next start from the project folder that is automatic. If you deploy a trimmed-down build (for example with output: 'standalone') and the route returns the error message, check that the data folder was included. Next.js has the outputFileTracingIncludes option to add extra files to the build output.
Good to know
- The
User-Agentis not security. Anyone can set it to anything, and some tools do not identify themselves. This feature is a convenience for humans in terminals, not an access check. Never put anything in the text view that you would not show on the website. - It is not just for curl. Any client whose header matches the regex gets the text, including scripts and monitoring tools using
python-requests. Remove a name from the regex if that is a problem. - Proxy runs on Node.js in Next.js 16. You cannot set
runtimein the file. This is a good fit for a self-hosted setup. - Keep
proxy.tslight. It runs before routes are rendered, so it should only read a header and pick a path. Reading files and other work belongs in the route handler.
Ideas to extend it
- Generate the text from real posts. Replace the
readFilecall with a function that builds the text from your own data (for example from your MDX posts) and loops over them to print each title, date and link. The proxy does not need to change. - Pagination, tag filters and search. Read
request.nextUrl.searchParamsin the route handler forpage,tagandq. Because the proxy preserves the query string,curl "blog.example.com/?tag=linux"already arrives with the parameters. - Clickable links. Many modern terminals support OSC 8 hyperlinks, an escape sequence that turns any text into a clickable link. Print the full URL as well, so terminals without support can still detect it.
- More files. Serve different text files for different pages, for example a
help.txtshown when someone requests/?help. - Plain output. Offer a version without colours for people who pipe the output into other tools.
Conclusion
With about thirty lines in proxy.ts and a tiny route handler, your site now answers differently depending on who asks. The pieces fit together like this:
proxy.tsinspects theUser-Agentand rewrites command-line clients to/blog.txt, keeping the query string and the original URL.app/blog.txt/route.tsreadsdata/example.txtand returns it astext/plain.Vary: User-Agentkeeps caches from mixing up the two versions of the same URL.colorize(optional) turns simple placeholders into ANSI colours.
Try it on your own site, then share the one-liner with your readers:
curl blog.example.com