TypeError: Cannot read properties of undefined (reading 'headers')
Unanswered
Silver carp posted this in #help-forum
Silver carpOP
Please i need help,
I'm making use of next-connect.
signin route ~ /api/signin/route.ts
I'm making use of next-connect.
const handler = () =>
routerHandler.use(async (req, res, next) => {
const authToken = getCookie("authToken", { req, res }) as string;
const refreshToken = getCookie("refreshToken", { req, res }) as string;
setAuthTokens(authToken, refreshToken);
console.log(`logging request example =====> ${req.method} ${req.url}`);
await next();
});
export default handler;
signin route ~ /api/signin/route.ts
import { NextResponse, type NextRequest } from "next/server";
import handler, { type RequestContext } from "@/lib/request-middleware";
import http from "@/services/server";
handler().post(async (req: NextRequest) => {
const { userEmail, userPassword } = await req.json();
try {
const res = await http.post(`/login`, {
email: userEmail,
password: userPassword,
});
const { data } = res.data;
console.log("=====>=====", data);
return NextResponse.json({ data });
} catch (err) {
console.log("========>", err);
return NextResponse.json(
{ message: "Error", err },
{
status: 500,
},
);
}
});
export const POST = async (req: NextRequest, ctx: RequestContext) => {
return handler().run(req, ctx);
};
10 Replies
Silver carpOP
server instance
import axios, { type AxiosInstance, type AxiosResponse } from "axios";
import config from "@/config";
const http: AxiosInstance = axios.create({
baseURL: config.apiUrl,
});
interface AuthTokens {
authToken: string | undefined;
refreshToken: string | undefined;
}
const authTokens: AuthTokens = {
authToken: "",
refreshToken: "",
};
export const setAuthTokens = (authToken: string, refreshToken: string) => {
authTokens.authToken = authToken;
authTokens.refreshToken = refreshToken;
};
http.interceptors.request.use(
(newConfig) => {
const configG = newConfig;
if (authTokens.authToken) {
configG.headers.Authorization = `Bearer ${authTokens.authToken}`;
}
configG.headers["Content-Type"] = "application/json";
return configG;
},
(error) => {
console.log("Error here===1===>", error);
return Promise.reject(error);
},
);
http.interceptors.response.use(
(response: AxiosResponse) => response,
(error) => {
console.log("Error here===2===>", error);
return Promise.reject(error);
},
);
export default http;
client instance
import axios from "axios";
import { deleteCookie } from "cookies-next";
import Router from "next/router";
const clientHttp = axios.create();
// const router = useRouter();
clientHttp.interceptors.response.use(
(response) => response,
(error) => {
console.log("errorr=======>", error);
if (error.response.status === 401) {
Router.push("/login");
deleteCookie("authToken");
deleteCookie("userMetaData");
deleteCookie("refreshToken");
} else {
const err =
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
Object.entries(error.response?.data?.data || {}).length > 0
? error.response.data.data
: error.response.data;
if (err.validation) {
err.message = err.validation.body.message;
}
return Promise.reject(err);
}
// Add a return statement here to handle other cases
// For example, you can return a Promise.reject with a generic error message
// eslint-disable-next-line prefer-promise-reject-errors
return Promise.reject("An error occurred. Please try again later.");
},
);
export default clientHttp;
Form
On form submit , i got the expected data from the endpoint but, i keep getting 500 internal server error on the network tab , i checked my terminal and also see this error :
const onSubmit = async (values: z.infer<typeof signInSchema>) => {
const v = values;
try {
const request = await clientHttp.post("/api/signin", {
userEmail: v.email,
userPassword: v.password,
});
console.log(request);
} catch (error) {
console.log("err", error);
}
};
On form submit , i got the expected data from the endpoint but, i keep getting 500 internal server error on the network tab , i checked my terminal and also see this error :
error TypeError: Cannot read properties of undefined (reading 'headers')
at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:266:61)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Please help
you should get rid of axios https://www.adios-axios.com
but the types for for route handlers isn't what you shared, it is just the nextrequest input and you return the response (ie no ctx)
but the types for for route handlers isn't what you shared, it is just the nextrequest input and you return the response (ie no ctx)
also i don't even think axios can be run on client side
Silver carpOP
what do you suggest i do please
Just use fetch requests for both server and client
Silver carpOP
thank you so much
but i still end up getting
but i still end up getting
Error: Network response was not ok
Silver carpOP
i guess i'll give ky a try