Home > Enterprise >  NextJs protected API with Next Auth
NextJs protected API with Next Auth

Time:09-17

I have a problem building NextJs Web with NextAuth. I created my own API in pages/api and protected it with getSession from NextAuth. When I call the API using getServerSideProps or getStaticProps, getSession returns a null value, but when I call the API inside a component function, getSession returns the user data value. Can anyone help or have any tips?

pages/index.jsx

export async function getStaticProps(context) {
  const projects = await fetchApi(`${process.env.BASE_URL}/projects`);
  console.log(projects)

  return {
    props: {},
  };
}

pages/api/projects

import { getSession } from 'next-auth/client';

async function handler(req, res) {
  const projectService = new ProjectService();

  let session;
  let emailUser;
  try {
    session = await getSession({ req });
    console.log(session);  // null
    emailUser = session.user.email;

    if (!session) {
      throw new AuthenticationError('No authenticated');
    }
  } catch (error) {
    if (error instanceof ClientError) {
      return res.status(error.statusCode).json(clientErrRes(error));
    }
  
    return res.status(500).json(serverErrRes(error));
  }

  ...another code
 }

CodePudding user response:

You can't have auth (per user) in getStaticProps because those pages are generated at compile time. When you are calling the api from the react component (at runtime - from the browser) you are doing it on the behalf of the user so there is a session (cookie) there.

CodePudding user response:

You need to add headers in the fetch from the context. because you are fetching from server side.

const {req}=context
const {cookie} = req.headers

return fetch(`${process.env.BASE_URL}/projects`, {
  headers: {
    'Cookie':cookie
  }
})
  • Related