Next.js Discord

Discord Forum

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

Unanswered
ayush_uidev posted this in #help-forum
Open in Discord
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();

          if (res.ok && user) {
            return user.user;
          }

          return user;
        } catch (error) {
          const errorMessage = (error as any)?.response?.data || null;
          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 };

1 Reply

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>
      )}
    </>
  );
}