CLIENT_FETCH_ERROR
when requesting to /api/auth/session
, reason: read ECONNRESET
#3330
-
When opening any private page (pages that rely on the session) I get this error on the first time I load them. But this only happens on the first time I load a private page right when I start the application, after this first load it doesn't happen again on the same page.
I have no idea what it might be. Is |
Beta Was this translation helpful? Give feedback.
Replies: 10 comments 25 replies
-
have a minimal reproduction? |
Beta Was this translation helpful? Give feedback.
-
It might. My way to bypass this problem, was to create a I'm not saying my solution is the best or fault-free. It supports our use case. Please adjust as you seem fit. import * as jwt from "next-auth/jwt"
import { NextApiRequestCookies } from "next/dist/server/api-utils"
/**
* Reads the JWT token from the next-auth session cookie, and returns the
* session object by decoding the token. Returns null if the JWT token is absent
* or invalid
*/
export async function getSessionFromCookie({
req,
}: {
req: { cookies: NextApiRequestCookies }
}) {
try {
// The cookie name differs between http and https urls. Also see here:
// https://github.com/nextauthjs/next-auth/blob/50fe115df6379fffe3f24408a1c8271284af660b/src/core/lib/cookie.ts#L56-L60
const isSecure = process.env.NEXT_PUBLIC_BASE_URL?.startsWith("https://")
const cookiePrefix = isSecure ? "__Secure-" : ""
const sessionToken = req.cookies?.[`${cookiePrefix}next-auth.session-token`]
// decode will throw when the token is invalid
const decoded = await jwt.decode({
token: sessionToken,
secret: String(process.env.COOKIE_SECRET_KEY),
})
if (!decoded) return null
return {
user: { id: String(decoded.sub) },
expires: new Date(Number(decoded.exp) * 1000).toISOString(),
}
} catch {
return null
}
} |
Beta Was this translation helpful? Give feedback.
-
The documentation says that the |
Beta Was this translation helpful? Give feedback.
-
my implementation for database sessions using prisma adapter: type Ctx = {
req: IncomingMessage;
};
const getUserAndSession = async (sessionToken: string): Promise<Session> => {
const { session, user } = await prismaAdapter.getSessionAndUser(sessionToken);
if (session && user) {
return {
expires: session.expires.toString(),
user,
};
}
return undefined;
};
const getToken = async (ctx: Ctx) => {
const cookies = parseCookies(ctx.req);
const token = cookies['next-auth.session-token'];
if (!token) return undefined;
return getUserAndSession(token);
}; parseCookies.ts: export function parseCookies(request: IncomingMessage): Record<string, any> {
const list = {};
const cookieHeader = request.headers?.cookie;
if (!cookieHeader) return list;
cookieHeader.split(`;`).forEach(function (cookie) {
// eslint-disable-next-line prefer-const
let [name, ...rest] = cookie.split(`=`);
name = name?.trim();
if (!name) return;
const value = rest.join(`=`).trim();
if (!value) return;
list[name] = decodeURIComponent(value);
});
return list;
} |
Beta Was this translation helpful? Give feedback.
-
Just thought I'd drop this here; it might help. Someone mentioned switching the This works to an extent. I don't know if anyone is running into this but when I try to use next-auth my dev session just crashes without any errors. |
Beta Was this translation helpful? Give feedback.
-
For me, It was 'getSession' mistakenly used in serverside. I replaced it to 'getServerSession' and problem solved. Hope it would help anyone. |
Beta Was this translation helpful? Give feedback.
-
Posting here just in case it helps someone, I had a slew of problems.
nextjs even output this nice warning below that I didn't read until I had spent far to much time trying to resolve this.
|
Beta Was this translation helpful? Give feedback.
-
I was running nextjs project on a port other than 3000, say 4200. we need to communicate this info to next-auth.
|
Beta Was this translation helpful? Give feedback.
-
I was running nextjs project on a port other than 3000, say 4200. we need to communicate this info to next-auth.
|
Beta Was this translation helpful? Give feedback.
-
I had additional code in my next.config.mjs file and as soon as I remove the code it worked for me. |
Beta Was this translation helpful? Give feedback.
It might.
getSession
is meant to run on the client. As it usesfetch
to request the user object from the session API route (/api/auth/session
) managed bynext-auth
, a single page request can result in multiple network requests ifgetServerSideProps
usesgetSession
to obtain the user information. Every time you'll invokegetSession
, the server will execute another network request against itself.My way to bypass this problem, was to create a
getSessionFromCookie
helper. A small function that reads the JWT token from the cookie header, and decodes that instead.I'm not saying my solution is the best or fault-free. It supports our…