reactjs – set url.pathname middleware nextJS with query graphql
import { NextMiddlewareResult } from "next/dist/server/web/types";
import { NextRequest, NextResponse } from "next/server";
export async function LocaleRedirectionMiddleware({
nextUrl,
}: NextRequest): Promise<NextMiddlewareResult | Promise<NextMiddlewareResult>> {
if (nextUrl.pathname !== "/") {
return null;
}
const response = await fetch('https://api.mywebsite/graphql/', {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
query: ` {
regions {
channel
language{
language
code
}
defaultLanguage {
code
language
}
}
}
}
}`
})
});
const data = await response.json();
const channel= data?.regions?.channel
const locale = data?.regions?.language.language
const url = nextUrl.clone();
url.pathname = `/${channel}/${locale}`;
return NextResponse.redirect(url);
}
export default LocaleRedirectionMiddleware;
In the provided code, these static variables are being used to modify the pathname property of the url variable, which is then used to create a new URL that includes the static values of channel and locale.
when i change the static variables with dynamic data from a query .
the result returned undefined.
localhost:3000/undefined/undefined
How can I solve this problem ??
Read more here: Source link
