javascript – Execute GraphQL mutation using Next.js API Routes

How can I execute a graphql mutation using an authenticated user and API Routes in Next.js. I tried to use generateClient() from aws-amplify/api but it throws NoSignedUser: No current user error.

const graphqlclient = generateClient();

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const body = req.body;

    if (!graphqlclient) return res.status(401).json({ message: 'Unauthorized' });

       const newProduct = body.newProduct;


       const results = await graphqlclient.graphql({
           query: createProduct,
           variables: {
               input: newProduct
           }
       })

       return res.status(200).json({ success: true, product: results });
    }

    res.status(405).json({ message: 'Method not allowed' });
}

I have also tried

const client = generateServerClientUsingCookies({
   config: amplifyConfig,
   cookies
});

but I get the error cookies was called outside a request scope.

Read more here: Source link