Issue with Axios
Answered
Scale parasitoid posted this in #help-forum
Scale parasitoidOP
Hi, in my code I have an AXIOS wrapper that adds a bunch of small features to all api requests, but when trying to build recent releases, I have been getting this error
I tried to change it to return null when not in development or server side, but the build process stops straight after. Could you help me please?
[ API ] : Failed to add client IP header: Error: Dynamic server usage: Route / couldn't be rendered statically because it used `headers`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error
at m (/var/www/TermedFrontend/.next/server/chunks/994.js:1:41170)
at d (/var/www/TermedFrontend/.next/server/chunks/512.js:1:10906)
at s.getClientIp (/var/www/TermedFrontend/.next/server/chunks/521.js:1:11295)
at async (/var/www/TermedFrontend/.next/server/chunks/521.js:1:10951)
at async aF.request (/var/www/TermedFrontend/.next/server/chunks/916.js:3:21146)
at async s.get (/var/www/TermedFrontend/.next/server/chunks/521.js:1:11546)
at async n (/var/www/TermedFrontend/.next/server/app/(normal)/page.js:2:23226)
at async c (/var/www/TermedFrontend/.next/server/app/(normal)/page.js:2:9306) {
description: "Route / couldn't be rendered statically because it used `headers`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error",
digest: 'DYNAMIC_SERVER_USAGE'
}
I tried to change it to return null when not in development or server side, but the build process stops straight after. Could you help me please?
Answered by B33fb0n3
alr. add this to your layout and your page.tsx:
export const dynamic = 'force-dynamic'
49 Replies
@Scale parasitoid Hi, in my code I have an AXIOS wrapper that adds a bunch of small features to all api requests, but when trying to build recent releases, I have been getting this error
js
[ API ] : Failed to add client IP header: Error: Dynamic server usage: Route / couldn't be rendered statically because it used `headers`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error
at m (/var/www/TermedFrontend/.next/server/chunks/994.js:1:41170)
at d (/var/www/TermedFrontend/.next/server/chunks/512.js:1:10906)
at s.getClientIp (/var/www/TermedFrontend/.next/server/chunks/521.js:1:11295)
at async (/var/www/TermedFrontend/.next/server/chunks/521.js:1:10951)
at async aF.request (/var/www/TermedFrontend/.next/server/chunks/916.js:3:21146)
at async s.get (/var/www/TermedFrontend/.next/server/chunks/521.js:1:11546)
at async n (/var/www/TermedFrontend/.next/server/app/(normal)/page.js:2:23226)
at async c (/var/www/TermedFrontend/.next/server/app/(normal)/page.js:2:9306) {
description: "Route / couldn't be rendered statically because it used `headers`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error",
digest: 'DYNAMIC_SERVER_USAGE'
}
I tried to change it to return null when not in development or server side, but the build process stops straight after. Could you help me please?
axios is dead: https://www.adios-axios.com/
You want to use
You want to use
fetch
. It includes everything that axios haveScale parasitoidOP
the API is important as the backend requires it as a system to stop multiaccounting and other backend projects. I tried to inject it using middleware aswell but it didn't work.
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export function middleware(request: NextRequest) {
const ip = request.headers.get("x-forwarded-for") || "Unknown IP";
const response = NextResponse.next();
response.headers.set("X-NEXT-CLIENT-IP", ip);
const currentUser = request.cookies.get("token")?.value;
if (
currentUser &&
(request.nextUrl.pathname.startsWith("/login") ||
request.nextUrl.pathname.startsWith("/register"))
) {
return NextResponse.redirect(new URL("/dash", request.url));
}
if (!currentUser && request.nextUrl.pathname.startsWith("/dash")) {
return NextResponse.redirect(
new URL(
`/login?redirect=${encodeURIComponent(request.nextUrl.pathname)}`,
request.url,
),
);
}
return response;
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|.*\\.png$|favicon.ico).*)"],
};
@B33fb0n3 axios is dead: https://www.adios-axios.com/
You want to use fetch. It includes everything that axios have
Scale parasitoidOP
my main issue seems to be with getting the client IP on build, rather than the api fetch system
Scale parasitoidOP
wait am i stupid
one sec
@B33fb0n3 why do you set an extra header, if you already have the ip inside your headers?
Scale parasitoidOP
I'm pretty sure it was due to some cloudflare issues, but i'm not 100% sure I was just asked to make it
@B33fb0n3 can you elaborate a bit more?
Scale parasitoidOP
"so it can't be spoofed, it just adds a bit more secuiryt"
thats what the dev said
backend dev, but I also don't understand why my code doesn;'t work and at this point I wanna figure out how I could fix it just so I could fix an issue like this in the future
@Scale parasitoid backend dev, but I also don't understand why my code doesn;'t work and at this point I wanna figure out how I could fix it just so I could fix an issue like this in the future
When you want to find a specific error, you want to have a clean workspace. So you might also want to remove unnecessary code, that probably produces these errors. That would help us a lot π
Also can you share your route handler?
Scale parasitoidOP
src
β£ app
β β£ (app)
β β β£ api
β β β β£ setToken
β β β β β route.ts
β β β β .placeholder
β β β£ [bio]
β β β β page.tsx
β β β ~
β β β β£ (auth)
β β β β β£ reset
β β β β β β page.tsx
β β β β β verify
β β β β β β page.tsx
β β β β£ 404
β β β β β page.tsx
β β β β£ 500
β β β β β page.tsx
β β β β£ banned
β β β β β page.tsx
β β β β£ test
β β β β β£ dev
β β β β β β page.tsx
β β β β β page.tsx
β β β β£ wip
β β β β β page.tsx
β β β β£ [slug]
β β β β β page.tsx
β β β β layout.tsx
β β£ (auth)
β β β£ forgot
β β β β page.tsx
β β β£ login
β β β β page.tsx
β β β£ register
β β β β page.tsx
β β β£ reset-password
β β β β page.tsx
β β β£ verify
β β β β page.tsx
β β β layout.tsx
β β£ (normal)
β β β£ layout.tsx
β β β page.tsx
β β£ dash
β β β£ layout.tsx
β β β page.tsx
β β£ error.tsx
β β£ globals.css
β β£ layout.tsx
β β not-found.tsx
β£ components
β β£ auth
β β β£ forgot
β β β β forgot.tsx
β β β£ login
β β β β login.tsx
β β β£ register
β β β β register.tsx
β β β£ reset
β β β β reset.tsx
β β β verify
β β β β verify.tsx
β β£ dashboard
β β β layout.tsx
β β£ global
β β β£ admin
β β β pages
β β β β£ footer.tsx
β β β β nav.tsx
β β£ home
β β β£ cta
β β β β cta.tsx
β β β£ features
β β β β features.tsx
β β β£ grid
β β β β grid.tsx
β β β hero
β β β β hero.tsx
β β£ profile
β β β£ banned
β β β β banned.tsx
β β β£ notfound
β β β β notfound.tsx
β β β£ page
β β β β£ message.tsx
β β β β page.tsx
β β β index.tsx
β β£ storage
β β β£ api.tsx
β β β base.tsx
β β ui
β β β£ button.tsx
β β β£ icons.tsx
β β β£ logo.tsx
β β β£ maraquee.tsx
β β β£ modal-video.tsx
β β β£ notification.tsx
β β β£ page-illustration.tsx
β β β£ redirect.tsx
β β β£ spotlight.tsx
β β β tooltip.tsx
β£ data
β β redirects.ts
β£ lib
β β£ Aos
β β β£ aos.css
β β β aos.tsx
β β£ data
β β β£ messages.ts
β β β socials.ts
β β£ prisma.ts
β β utils.ts
β£ modules
β β£ Body
β β β£ Body.css
β β β Body.tsx
β β£ Console
β β β Console.tsx
β β£ Link
β β β index.tsx
β β£ meta.tsx
β β metagen.tsx
β£ prisma
β β schema.prisma
β£ styles
β β utils.css
β£ types
β β index.d.ts
β£ utils
β β£ api
β β β£ debugLog.ts
β β β getStats.ts
β β£ server
β β β£ auth.ts
β β β£ dashboard.ts
β β β£ email.ts
β β β£ fetch.ts
β β β profile.ts
β β£ toasts.tsx
β β£ uppercaseFirst.ts
β β£ useMasonry.tsx
β β useMousePosition.tsx
β middleware.ts
I use the APP dir
if thats what you're asking
API requests are handled on a seperate go server
no I mean more the code of your route handler. Not the folder structure π
Also remove the headers that I mentioned and maybe other code that is unnecessary
Also remove the headers that I mentioned and maybe other code that is unnecessary
@B33fb0n3 no I mean more the code of *your* route handler. Not the folder structure π
Also remove the headers that I mentioned and maybe other code that is unnecessary
Scale parasitoidOP
Sorry I'm a bit stupid I don't know what you mean by route handler
I also recoded it using fetch rather than axios
@Scale parasitoid Sorry I'm a bit stupid I don't know what you mean by route handler <:Sob:1232609083757035571>
inside your nextjs app you can defined "route handlers". Others name them "api routes" or maybe even another term. You are using a route handler here (as you error message shows). Inside that route handler this error is thrown. So I want to take a look at the route handler (copy paste the whole file to for example pastebin or any other plattform).
More about route handlers:
https://nextjs.org/docs/app/building-your-application/routing/route-handlers
More about route handlers:
https://nextjs.org/docs/app/building-your-application/routing/route-handlers
Scale parasitoidOP
Ohhh
import type { ResponseProp } from "@/types";
/*
Copyright Β© 2024 Kars (github.com/kars1996)
Not to be shared, replicated or used without prior consent.
Contact Kars for any enquiries
*/
const Data: ResponseProp = {
response: "Logged Out",
status: 200,
};
export async function GET(): Promise<Response> {
const response = new Response(JSON.stringify("Signed Out"), {
status: 200,
});
response.headers.set(
"Set-Cookie",
"token=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0",
);
return new Response(JSON.stringify(Data), {
status: Data.status,
headers: {
"Content-Type": "application/json",
},
});
}
I have one route handler here that isn't even really in use
"use server";
import "server-only";
import type { StatsProp } from "@/types";
import api from "../server/fetch";
export async function getStats(): Promise<StatsProp> {
return await api.get<StatsProp>("/stats");
}
however the API wrapper is used multiple times to fetch stuff
including authentication and stuff
so I belive the issue was in prerendering everything, the code tried to create a header which isn't allowed and caused a error
which nextjs version are you using?
Scale parasitoidOP
15.0.3
@B33fb0n3 can you also return your created response instead of creating a new response?
Scale parasitoidOP
yeah I should probably do that
done
but the route wasn't even being used
can you share the page with the path
/
? It seems like you are using headers somewhere there@Scale parasitoid but the route wasn't even being used
Before sharing it, can you add this to your page.tsx:
export const dynamic = 'force-dynamic'
@Scale parasitoid ts
"use server";
import "server-only";
import type { StatsProp } from "@/types";
import api from "../server/fetch";
export async function getStats(): Promise<StatsProp> {
return await api.get<StatsProp>("/stats");
}
Scale parasitoidOP
this is the only instance of it being called in the index route, and this is the only instance of it being used
export const dynamic = 'force-dynamic'
import CTA from "@/components/home/cta/cta";
import Features from "@/components/home/features/features";
import Grid from "@/components/home/grid/grid";
import Hero from "@/components/home/hero/hero";
import Link from "next/link";
/*
Copyright Β© 2024 Kars (github.com/kars1996)
Not to be shared, replicated or used without prior consent.
Contact Kars for any enquiries
*/
export default function IndexPage() {
return (
<main className="relative flex grow flex-col">
<Hero />
<Features />
<Grid />
<CTA />
</main>
);
}
import Footer from "@/components/global/pages/footer";
import Nav from "@/components/global/pages/nav";
import { cookies } from "next/headers";
/*
Copyright Β© 2024 Kars (github.com/kars1996)
Not to be shared, replicated or used without prior consent.
Contact Kars for any enquiries
*/
export default async function DefaultLayout({
children,
}: {
children: React.ReactNode;
}) {
const cookieStore = await cookies();
const token = cookieStore.get("token");
return (
<div>
<Nav isAuth={token ? true : false} />
{children}
<Footer />
</div>
);
}
@Scale parasitoid tsx
import Footer from "@/components/global/pages/footer";
import Nav from "@/components/global/pages/nav";
import { cookies } from "next/headers";
/*
Copyright Β© 2024 Kars (github.com/kars1996)
Not to be shared, replicated or used without prior consent.
Contact Kars for any enquiries
*/
export default async function DefaultLayout({
children,
}: {
children: React.ReactNode;
}) {
const cookieStore = await cookies();
const token = cookieStore.get("token");
return (
<div>
<Nav isAuth={token ? true : false} />
{children}
<Footer />
</div>
);
}
alr. add this to your layout and your page.tsx:
export const dynamic = 'force-dynamic'
Answer
Scale parasitoidOP
so if i just forced all of them to be dynamic it works??
π
yeah that fixed it
thanks so much
@Scale parasitoid so if i just forced all of them to be dynamic it works??
well.. you are using headers. Headers are different for each client. So serving it static will result in security vulnerabilities
happy to help
@B33fb0n3 well.. you are using headers. Headers are different for each client. So serving it static will result in security vulnerabilities
Scale parasitoidOP
thank you very much
much appreciated
have a nice day
u 2