2

I'm using NextJs 13 beta version that has introduced /app directory. Along with this I'm using Next-Auth for authentication purpose. Basic login and logout functionality is working as expected, also in one of my server component if I do const session = await getServerSession(authOptions); session variable contains user information as expected.

My NextAuthOptions looks like this

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  secret: process.env.NEXTAUTH_SECRET,
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET as string
    })
  ],
  session: { strategy: 'jwt' },
  callbacks: {
    async jwt({ token, account, user }) {
      if (account) {
        token.id = user?.id;
      }
      return token;
    },
    async session({ session, token }) {
      // Send properties to the client, like an access_token and user id from a provider.
      if (session.user) session.user.id = token.id;
      return session;
    }
  }
};

Now in one of my another server component I'm trying to fetch a data from API which should ideally be auth protected. My server component fetch looks like this

  const res = await fetch('http://localhost:3000/api/protected');
  const json = await res.json();
  if (json.content) {
    console.log('RES:', json.content);
  }

And my API code pages/api/protected.ts (I've purposely kept in pages folder and not in app, this is not an issue) looks something like

// This is an example of to protect an API route
import { getServerSession } from 'next-auth/next';
import { authOptions } from '../../app/api/auth/[...nextauth]/route';

import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const session = await getServerSession(req, res, authOptions);
  console.log('HEADER::::', req.headers);
  console.log('SESSION::::', session);

  if (session) {
    return res.send({
      content:
        'This is protected content. You can access this content because you are signed in.'
    });
  }

  res.send({
    error: 'You must be signed in to view the protected content on this page.'
  });
}

Now when my server component is making a fetch request it is not able to find the session in my API protected.ts, but when I hit the URL http://localhost:3000/api/protected from the browser, the session is being found in the protected.ts API and i getting logged along with user details

My issue is how can i send session information to the API from my server component in order to my the API auth protected

Jawad
  • 103
  • 1
  • 8

0 Answers0