Questions about MIDDLEWARE
Answered
Palomino posted this in #help-forum
PalominoOP
Where does middleware operate? Apparently the middleware needs to follow edge runtime and that means I cannot do file stuff on my server. for routes and so on
Answered by Arinji
Middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/api')) {
const contentType = request.headers.get('content-type')
if (contentType !== 'application/json') {
return new NextResponse(
JSON.stringify({ message: 'Only JSON content type is allowed' }),
{
status: 415,
headers: { 'Content-Type': 'application/json' }
}
)
}
}
return NextResponse.next()
}
export const config = {
matcher: '/api/:path*',
}27 Replies
yes its on the edge
PalominoOP
yeah no
anyways, im trying to check induvidual API routes if they have
req.json() in them, cuz I need to check content type. and I thought it would work in middleware but apparently not.Wdym req.json() checking btw...
Do you want to check if the response you got has a content type of json?
@Arinji Do you want to check if the response you got has a content type of json?
PalominoOP
Yes, when req.json() fails to parse, it crashes the server. But when i think about it, i can do
const payload = (await req.json()) || {};
const payload = (await req.json()) || {};
Or better yet, you can check for it in your Middleware and return an error or smthn if needed :)
You get access to headers in the middleware
Check content type
Chestnut-sided Warbler
Middleware will be able to use the Node.js runtime soon™️ - https://github.com/vercel/next.js/discussions/46722#discussioncomment-11030344
Soon
That's been cooking for so long it's insane
They did announce its coming for v15, with use cache being stable i think
Chestnut-sided Warbler
It would simplify a lot of stuff, I want to set GeoIP headers the way Vercel does but without
fs in middleware it's very awkwardIkr lmao, it was a very dumb decision by them
I host my websites on a vps
My vps does not have edge
So why are y'all forcing me to use your edge runtime lmao
Which is essentially just limited node if you aren't using vercel
Anyways, side tangent.. let's get back on topic
Middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/api')) {
const contentType = request.headers.get('content-type')
if (contentType !== 'application/json') {
return new NextResponse(
JSON.stringify({ message: 'Only JSON content type is allowed' }),
{
status: 415,
headers: { 'Content-Type': 'application/json' }
}
)
}
}
return NextResponse.next()
}
export const config = {
matcher: '/api/:path*',
}Answer
@Palomino that's how you check content type
PalominoOP
Yeah, only issue is when the route doesnt need json, i guess ill edit each file for now :)