0

So I am trying to develop the next app with a protected API route. When is simply use browser to call the API it response the output but when I use from client call It return null,

Output when I do call from browser

Console Log Output

But when I do from client-side it returns null

Client Side console

Next Js client side

export async function getServerSideProps() {
const res = await fetch(`${host}/api/categories`);
const categories: DataC = await res.json();

const resS = await fetch(`${host}/api/subcategories`);
const subcategories: DataS = await resS.json();


const resProducts = await fetch(`${host}/api/addproducts`,);
const products: productRes = await resProducts.json();

return (.....)
}

Next JS Api part

import type { NextApiRequest, NextApiResponse } from 'next'
import { Category, PrismaClient, Subcategory } from '@prisma/client'
import { getSession } from 'next-auth/react';

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse<Data>
) {
    try {
        const session = await getSession({ req });
        console.log(session);
        .......
     }catch (error) {
        console.log(error);
        res.status(500).json({ success: false, product: null });
    }
}

I Have also tried with credentials: 'include', credentials: 'same-site' but it didn't work

EDIT:

[https://stackoverflow.com/questions/69057271/why-are-cookies-not-sent-to-the-server-via-getserversideprops-in-next-js][4]

Here is the solution

Mahafuz Zaman
  • 95
  • 1
  • 1
  • 5
  • I Have also tried with credentials: 'include', credentials: 'same-site' but it didn't work – Mahafuz Zaman Feb 10 '22 at 15:10
  • 1
    The api endpoint is on the same origin as the spa? – Andrew Gillis Feb 10 '22 at 15:49
  • [https://stackoverflow.com/questions/69057271/why-are-cookies-not-sent-to-the-server-via-getserversideprops-in-next-js](https://stackoverflow.com/questions/69057271/why-are-cookies-not-sent-to-the-server-via-getserversideprops-in-next-js) Here is the solution – Mahafuz Zaman Feb 10 '22 at 16:32
  • You shouldn't be calling API routes from `getServerSideProps`. Just use the API route logic directly inside `getServerSideprops` - it would prevent the issue altogether. See https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props#getserversideprops-or-api-routes. – juliomalves Feb 12 '22 at 15:32

0 Answers0