I am coding with Next.js v13.
You can find the codes I wrote by looking towards the end of this text.
working principle: 1- I'm throwing requests and values to the service that makes a fetch with a client side component.
2- The service receives the incoming request and sends it to the API.
3- the request goes through a "middleware.js" before going to the api
3.1 - reaching api if middleware allows request
3.2 - If the middleware does not allow the request, it performs the necessary actions and redirects to a different page with NextResponse.redirect(...).
my problem: I trigger my middleware when I go to a normal page and this NextResponse.redirect(...) operation works fine. HOWEVER! Unfortunately, when I send a request to an api, it doesn't work.
Fetch operation in api requests returns data as res.json().
and I'm returning a redirect from the middleware with NextResponse.redirect(...) only.
I think the question is related to this, but I would appreciate it if you could examine it and let me know.
please fallow the steps. page.js > service(postAPI) > middleware > API
page.js (runing when onSubmit)
await postAPI("/auth/sendVerifyEmail", values).then((data) => {
if(!data){
toast.error("Bir hata oluştu. Lütfen daha sonra tekrar deneyiniz.");
setIsloading(false);
return;
}
else{
if (data.status === "success") {
setIsAccessing(true);
setIsloading(false);
toast.success(data.message + " Lütfen Bekleyin, yönlendiriliyorsunuz...");
//Bilgi verir ve 5 saniye sonra login sayfasına yönlendirir.
const timeOut = setInterval(() => {
if(data.role){
setIsloading(false);
router.push(`/auth/login/${data.role.toLowerCase()}`);
}
else{
setIsloading(false);
router.push(`/`);
}
clearInterval(timeOut);
}, 4000);
} else {
toast.error(data.message);
setIsloading(false);
}
}
});
service(postAPI) running when onsubmit from page.js
export async function postAPI(URL, body = "", method="POST", headers = {'Content-Type': 'application/json'}){
try {
const data = await fetch (`${process.env.NEXT_PUBLIC_API_URL + URL}`,{
method: method,
headers: headers,
body: JSON.stringify(body)
}).then(res => res.json())
.catch(err => console.log(err))
return data;
} catch (error) {
throw new Error(`API request failed: ${error.message}`);
}
}
middleware.js (running middleware when service post to api)
export async function middleware(req, res, next) {
const { pathname } = new URL(req.url) || new URL(req.nextUrl);
console.log("pathname : " + pathname)
console.log(data);
if (
// istek gidecek sayfaları burada belirledik. eğer bu sayfalara istek giderse kontrol edilecek
(pathname.startsWith('/api/auth/verifyEmail')) && (req.method === "POST")
) {
//triggered on api request but not working!
//triggers and works for the page!
return NextResponse.rewrite(targetUrl);
}
else{
// kullanıcı limiti aşmadı ise isteği gönderir.
return NextResponse.next();
}
}
}
API API ONLY : OPERATES WITH VALUES SENT TO API AND RETURNS OBJECTS BACK
like this: return res.status(401).json({status: "error", error: error?.message, message: error?.message});
In these structures, I cannot use rewrite or redirect structures in api requests.
there is only one error i got back room: "SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"
I think it's because I returned it as res.json in the service section but when I deleted it my problem still wasn't resolved...
As @LajosArpad said, I encountered this problem because I did not use the structure I returned as response correctly.