I have this following route which exists src/app/test/page.tsx
"use client";
import axios from "axios";
import { useState, useEffect } from "react";
async function getRandom() {
try {
const response = axios.get(
"http://api.localhost/api-admin/auth/random"
);
return response;
} catch (error) {
return error;
}
}
const page = () => {
useEffect(() => {
getRandom().then((response) => {
console.log(response); //gets data
});
}, []);
return <div>test</div>;
};
export default page;
When i do this i get back data in the client side.
However when I do it in server.side (middleware and api) , i keep getting cors origin error
src/Middleware.ts
import { NextResponse, NextFetchEvent } from "next/server";
import type { NextRequest } from "next/server";
import axios from "axios";
const getData = async () => {
try {
const response = await axios.get(
"http://api.localhost/api-admin/api/auth/random"
);
return response;
} catch (error) {
return error;
}
};
export async function middleware(request: NextRequest, event: NextFetchEvent) {
const response = NextResponse.next();
const result = await getData();
return response;
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
"/((?!api|_next/static|_next/image|favicon.ico).*)",
],
};
In src/app/api/test/route.ts
import axios from "axios";
export async function GET() {
try {
const res = await axios.get(
"http://api.localhost/api-admin/auth/random"
);
return Response.json({ message: "hello", data: res.data });
} catch (error) {
return error;
}
I am not sure if I need to set up the cors header or modify the next.config.js .