401 Unauthorized when using server side data fetching and generateStaticParams()
Unanswered
West African Lion posted this in #help-forum
West African LionOP
I'm at a loss guys hoping y'all can help out.
I have a NextJS app deployed on Vercel.
I have two pages that grab data from the server. One is my / page
It has this method
This is what gets logged out when I yarn build or deploy to vercel
Now this is wild because my endpoint has never and currently doesn't require auth and has no code that returns a 401.
This also happens in another page that calls the same endpoint to generateStaticParams
Is there some reason why I'm getting 401s? Help lol
I have a NextJS app deployed on Vercel.
"next": "14.0.3", // Version in package.jsonI have two pages that grab data from the server. One is my / page
It has this method
const getData = async () => {
const response = await fetch(
`${process.env.LIVE_API_URL!}/api/foo/search?term=&page=1&pageSize=10`
);
if (!response.ok) {
throw new Error(
`Failed to fetch foos, received status ${response.status} ${
response.statusText
}
URL: ${response.url}
Response Body: ${JSON.stringify(response.body, null, 2)}
Response Headers: ${JSON.stringify(response.headers, null, 2)}
`
);
}
const { results, pagination } = await response.json();
return {
initialFoos: results,
pagination,
};
};This is what gets logged out when I yarn build or deploy to vercel
Error: Failed to fetch foos, received status 401 Unauthorized
URL: https://redacted.vercel.app/api/foo/search?term=&pageSize=10&page=1
Response Body: {}
Response Headers: {}Now this is wild because my endpoint has never and currently doesn't require auth and has no code that returns a 401.
import { NextRequest, NextResponse } from "next/server";
import { getConnection } from "@/lib/mongo/mongo";
export async function GET(req: NextRequest) {
try {
const client = await getConnection();
const db = client.db("redacted");
const { searchParams } = new URL(req.url);
const term = searchParams.get("term") || "";
const page = parseInt(searchParams.get("page") || "1", 10);
const pageSize = searchParams.has("pageSize")
? parseInt(searchParams.get("pageSize") || "10", 10)
: -1;
const foos= db.collection("foos");
const query = term
? {
$or: [
{ name: new RegExp(term as string, "i") },
{ company: new RegExp(term as string, "i") },
],
}
: {};
let results;
let totalResults;
if (pageSize === -1) {
// Return all documents without pagination
results = await foos.find(query).toArray();
totalResults = results.length;
return NextResponse.json({
results,
pagination: {
page: 1,
pageSize: totalResults,
totalResults,
totalPages: 1,
},
});
} else {
// Apply pagination
results = await foos
.find(query)
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray();
totalResults = await foos.countDocuments(query);
return NextResponse.json({
results,
pagination: {
page,
pageSize,
totalResults,
totalPages: Math.ceil(totalResults / pageSize),
},
});
}
} catch (e: any) {
console.error("The error received : " + e);
return NextResponse.json({ error: e.message }, { status: 500 });
}
}This also happens in another page that calls the same endpoint to generateStaticParams
export async function generateStaticParams() {
try {
const fooUrl=
process.env.LIVE_API_URL! + "/api/foo/search?pageSize=-1";
console.log("fooUrl: ", fooUrl);
const fooResponse= await fetch(fooUrl);
if (!fooResponse.ok) {
throw new Error(
`Failed to fetch foos, received status ${fooResponse.status}`
);
}
const fooResponseData = await fooResponse.json();
console.log(
"fooResponseData: ",
JSON.stringify(fooResponseData, null, 2)
);
const foos = fooResponseData.results;
console.log(JSON.stringify(foos, null, 2));
return foos.map((foo: any) => ({
fooName: encodeURIComponent(foo.name),
}));
} catch (error: any) {
console.error(error);
return [];
}
}Is there some reason why I'm getting 401s? Help lol
2 Replies
West African LionOP
For reference, I can make the request with my browser and get the searched data I expect.
This is logged in vercel as a status 200 response
When I run yarn build, it gives a 401 with a request user agent of node.
I don't see the difference and how this is happening?
This is logged in vercel as a status 200 response
When I run yarn build, it gives a 401 with a request user agent of node.
I don't see the difference and how this is happening?
West African LionOP
It was the vercel authentication setting here - /settings/deployment-protection
Basically because I have my new endpoints deployed to a staging branch it was requiring vercel auth to view the deployment hence the build process was failing.
I feel like there has to be an easier way to roll out api changes so builds don't fail when they include SSR data fetching changes as well
Basically because I have my new endpoints deployed to a staging branch it was requiring vercel auth to view the deployment hence the build process was failing.
I feel like there has to be an easier way to roll out api changes so builds don't fail when they include SSR data fetching changes as well