Laravel like middleware in NextJS api routes
Answered
Dwarf Crocodile posted this in #help-forum
Dwarf CrocodileOP
In laravel and i think express (i haven't used it personally but i've seen examples), middlewares are applied to individual routes. Because the routes are defined in code you can make this very simple like the laravel example below which adds a "IsAdmin" middleware to the route /hello
Route::middleware([IsAdmin::class])->get("/hello", fn() => "Hello");
I haven't really understood nextjs's middlewares is the example above something trivial to acheive especially for api routes or would i need to do manual checks in each route.ts export?
Route::middleware([IsAdmin::class])->get("/hello", fn() => "Hello");
I haven't really understood nextjs's middlewares is the example above something trivial to acheive especially for api routes or would i need to do manual checks in each route.ts export?
Answered by Toyger
nextjs use different approach for that, unfortunately.
you have single middleware file, where you define routes which you want to be handled by it, most of time with regex.
if you have different logic for different paths, then you'll need to have conditions that separate logic for them, but still everything will be in same middleware.js file
you have single middleware file, where you define routes which you want to be handled by it, most of time with regex.
if you have different logic for different paths, then you'll need to have conditions that separate logic for them, but still everything will be in same middleware.js file
3 Replies
Toyger
nextjs use different approach for that, unfortunately.
you have single middleware file, where you define routes which you want to be handled by it, most of time with regex.
if you have different logic for different paths, then you'll need to have conditions that separate logic for them, but still everything will be in same middleware.js file
you have single middleware file, where you define routes which you want to be handled by it, most of time with regex.
if you have different logic for different paths, then you'll need to have conditions that separate logic for them, but still everything will be in same middleware.js file
Answer
Dwarf CrocodileOP
Is this planned to change? This seems really dumb especially as you handle bigger and bigger projects.
Toyger
I saw some issues and discussions on github, but looks like it's not an important feature for dev team.