Passing and Accessing Authentication Tokens from External Backend to Client-side Components in Next.

How can I pass the authentication token obtained from an external backend to client-side components in Next.js when using Next-Auth for authentication? I am currently using const session = await getServerSession(authOptions); in server-side components, but how can I access the session in client-side components? dir app/api/auth/[...nextauth]
export const authOptions: NextAuthOptions = {
session: {
strategy: "jwt",
},
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
},
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
try {
const res = await fetch(
"http://ec2-...../api/admin/signIn",
{
method: "POST",
body: JSON.stringify(credentials),
headers: { "Content-Type": "application/json" },
}
);
const user = await res.json();
return user;
} catch (error) {
throw new Error(
errorMessage ? JSON.stringify(errorMessage) : String(error)
);
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.role = user.role;
token.name = user.name;
token.token = user.token;
}
return token;
},
async session({ session, token, user }) {
if (token) {
session.user.role = token.role;
session.user.name = token.name;
session.user.token = token.token;
}
return session;
},
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
export const authOptions: NextAuthOptions = {
session: {
strategy: "jwt",
},
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
},
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
try {
const res = await fetch(
"http://ec2-...../api/admin/signIn",
{
method: "POST",
body: JSON.stringify(credentials),
headers: { "Content-Type": "application/json" },
}
);
const user = await res.json();
return user;
} catch (error) {
throw new Error(
errorMessage ? JSON.stringify(errorMessage) : String(error)
);
}
},
}),
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.role = user.role;
token.name = user.name;
token.token = user.token;
}
return token;
},
async session({ session, token, user }) {
if (token) {
session.user.role = token.role;
session.user.name = token.name;
session.user.token = token.token;
}
return session;
},
},
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
5 Replies
ayush_uidev
ayush_uidevOP2y ago
the code that i used for page.tsx
const getUniData = async (): Promise<UniData> => {
const session = await getServerSession(authOptions);

const res = await fetch(
"http://ec2-3-110-...api/uni/getAllUniversity?label=UNI",
{
next: { tags: ["uni"] },
headers: {
"x-access-token": session?.user.token as string,
},
}
);
// Recommendation: handle errors
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error("Failed to fetch data");
}

const response = res.json();

return response;
};

export default async function Home() {
const session = await getServerSession(authOptions);
const uniData = await getUniData();
return (
<>
<h1>Hello Nextjs</h1>
{session?.user && (
<div>
{uniData.data?.map((uni) => (
<p key={uni._id}>{uni.name}</p>
))}
</div>
)}
</>
);
}
const getUniData = async (): Promise<UniData> => {
const session = await getServerSession(authOptions);

const res = await fetch(
"http://ec2-3-110-...api/uni/getAllUniversity?label=UNI",
{
next: { tags: ["uni"] },
headers: {
"x-access-token": session?.user.token as string,
},
}
);
// Recommendation: handle errors
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error("Failed to fetch data");
}

const response = res.json();

return response;
};

export default async function Home() {
const session = await getServerSession(authOptions);
const uniData = await getUniData();
return (
<>
<h1>Hello Nextjs</h1>
{session?.user && (
<div>
{uniData.data?.map((uni) => (
<p key={uni._id}>{uni.name}</p>
))}
</div>
)}
</>
);
}
rocawear
rocawear2y ago
Client API | NextAuth.js
The NextAuth.js client library makes it easy to interact with sessions from React applications.
ayush_uidev
ayush_uidevOP2y ago
thanks for answering i have a form which i am using "use client" how can i access the session token when i submit maybe that can be done with provider but it provides session data inside network tab in browser inspect if it is possible to not show the session the problem is i have to send token in headers each time i fetch and i dont like calling getServerSession on every page is there a better way to handle it ? @rocawear @ranthom-merge I maybe not asking the problem correctly i am pretty new to nextjs world
rocawear
rocawear2y ago
I would make function that adds token to it. Something like this:
const fetchWithToken = async (url, options = {}) => {
const session = await getSession();

options.headers = {
...options.headers,
Authorization: `Bearer ${session.user.token}`,
};

return fetch(url, options);
};

export default fetchWithToken;
const fetchWithToken = async (url, options = {}) => {
const session = await getSession();

options.headers = {
...options.headers,
Authorization: `Bearer ${session.user.token}`,
};

return fetch(url, options);
};

export default fetchWithToken;
ayush_uidev
ayush_uidevOP2y ago
i tried it but i think i need to handle some bits on client side and it is not possible to hide session thanks you i will try this did not work that well but i will try figuring out this problem some other time thanks i am marking it as done
Want results from more Discord servers?
Add your server