Не получается обратиться к серверу

Мне нужно проверять пользователя на то что он зарегистрирован. Это я делаю в файле _app.tsx:

const MyApp = ({ Component, pageProps }: AppProps) => {
    // code
}

export async function getInitialProps(ctx:NextPageContext) {
    if (!ctx.req) return { props: { } };
    
    const cookie = ctx.req.headers.cookie!;
    const response = await fetch(`${process.env.API_URL}/api/auth/auth`, {
        headers: { cookie }
    })
    const data = await response.json();

    return {
        props: { data }
    }
}

export default MyApp;

На сервере отрабатываю через middleware, но он никак не отзывается (console.log(1)):

const authenticated = (fn: any) => async (req: IGetUserAuthInfoRequest, res: NextApiResponse) => {
    const { method, cookies } = req;

    console.log(1); // не выводится

    if (method === "OPTIONS") {
        return fn(req, res);
    }

    try {
        const token = cookies.token;
        const decoded = verify(token, `${process.env.JWT_KEY}`);

        if (!decoded) {
            return res.status(500).json({
                success: false, message: "Sorry you are not authenticated"
            })
        }

        req.user = decoded;

        return await fn(req, res);
    } catch (e: any) {
        return res.status(500).json({
            success: false, message: "Sorry you are not authenticated: " + e.message
        })
    }
}

export default authenticated;

Сама функция на сервере выглядит так:

import authenticated from "../middleware/auth.middleware";

export default authenticated(async function auth(req: IGetUserAuthInfoRequest, res: NextApiResponse) {
    const { method } = req;

    if (method === "GET") {
        try {
            const user: any = req.user;
            const payload = { email: user.email, id: user.id };
            const token = jwt.sign(payload, `${process.env.JWT_KEY}`, { expiresIn: "24h" });

            return res.status(200).json({ success: true, token });
        } catch (e: any) {
            console.log(e);
            res.status(500).json({ success: false, message: `Server error, try again: ${e.message}` });
        }
    } else {
        res.status(405).json({
            message: "We only supported GET"
        });
    }
});

При логине я все сохраняю в Cookie:

res.setHeader("Set-Cookie", cookie.serialize("token", token, {
    httpOnly: true,
    secure: process.env.NODE_ENV !== "development",
    sameSite: "strict",
    maxAge: 3600,
    path: "/"
}));

Короче проблема в том, что сервер ничего не возвращает, даже console.log(1)


Ответы (1 шт):

Автор решения: Алексей Яковлев

Обратился к серверу через React.useEffect() и все заработало:

auth:

export default async function auth() {
    const response = await fetch(`${process.env.API_URL}/api/auth/auth`, {
        headers: {
            Authorization: `Bearer ${Cookies.get("token")}`
        }
    });
    const data = await response.json();

    return { data, response };
}

В _app написал это:

React.useEffect(() => {
        async function load() {
            const { data, response } = await auth(); // здесь получаю ответ
        }

        load();
}, []);

→ Ссылка