How to use cookie authentication using “use server”

I’m working with Next.js and using JWT tokens for authentication. After logging in, I set the token in cookies. It works perfectly on localhost, but after deployment on the server, it’s not functioning as expected. It works fine on the domain when using “use client,” but not with “use server.”

Any suggestions?

Is there any implementation from backend just like cors?

i m sharing code with dummy api url

Working code in localstorage

"use server";

import { cookies } from "next/headers";
import Details from "../Account-Closure/details";

const fetchDummyDataWithToken = async () => {
  try {
    const cookieStore = cookies(); // Direct call without await
    const token = (await cookieStore).get("token")?.value;

    if (!token) {
      throw new Error("Token not found in cookies");
    }

    const response = await fetch(
      "https://api.co.in",
      {
        method: "GET",
        headers: {
          Authorization: Bearer ${token}, 
          "Content-Type": "application/json", // Optional: add content type
        },
      }
    );

    if (!response.ok) {
      throw new Error(Failed to fetch data. Status: ${response.status});
    }

    return response.json();
  } catch (error) {
    console.error("Error fetching data:", error);
    return null;
  }
};

const DummyApiPage = async () => {
  const apiResponse = await fetchDummyDataWithToken();

  if (!apiResponse) {
    return <div>Error fetching data. Please try again later.</div>;
  }
  console.log(apiResponse);
  const { result, data } = apiResponse;
  const { basic_details, dp_details } = data;

  return (
    <div style={{ padding: "20px", fontFamily: "Arial" }}>
      <h1>API Response</h1>
      <pre>{JSON.stringify(apiResponse, null, 2)}</pre>
      <section>
        <h2>Result</h2>
        <p>Flag: {result.flag}</p>
        <p>Message: {result.flag_message}</p>
      </section>
      <section>
        <h2>Basic Details</h2>
        <ul>
          <li>UCC Code: {basic_details.ucc_code}</li>
          <li>PAN: {basic_details.pan}</li>
          <li>Account Status: {basic_details.account_status}</li>
          <li>Date of Birth: {basic_details.date_of_birth}</li>
        </ul>
      </section>
      {/* DP Details Section */}
      <section>
        <h2>DP Details</h2>
        <ul>
          {dp_details.map((dp: any, index: any) => (
            <li key={index}>
              <strong>Depository:</strong> {dp.depository} <br />
              <strong>BO ID:</strong> {dp.bo_id} <br />
              <strong>Client ID:</strong> {dp.client_id} <br />
              <strong>Status:</strong> {dp.dp_status} <br />
              <strong>Primary Flag:</strong> {dp.primary_flag}
            </li>
          ))}
        </ul>
      </section>
    </div>
    // <>adasdahsdahsd</>
  );
};

export default DummyApiPage;

0

This is how i have done in multiple projects
create a helper file for server only

srcserverhelper.ts

import 'server-only';
export enum COOKIES {
  JWT = 'token',
  RESEND_OTP_JWT = 'resend-otp-token',
  ACCEPT_COOKIES_POLICY = 'acceptCookies',
}
export const setSecureJwt = (tkn: string) => {
  cookies().set(COOKIES.JWT, tkn, {
    secure: true,
    httpOnly: true,
    sameSite: true,
  });
};
export const getAuthorizationHeader = () => {
  const token = cookies().get(COOKIES.JWT)?.value;
  if (!token) return false;
  return { Authorization: 'Bearer ' + token };
};

then create server action for login

srcserveractionsauth.actions.ts

// You can generate this token, or you can get it
// from your backend server in case your backend is on another
// server and then call the helper function
  setSecureJwt(jwt);

Create a data-lib for tours and there you can use getAuthorizationHeader helper
function

srcserverdata-libtour.data-lib.ts

import 'server-only';

import { Roles } from '@/enums';
import { REQUEST_METHODS } from '@/server/enums/shared';
import {
  getAuthorizationHeader,
  getNodeRequiredRequestHeaders,
  getCacheKey,
} from '@/server/helper';
import { getServerError } from '@/server/server-error';
import { APIResponse, ToursDetailsType } from '@/types';
import { createTourRequestURL } from '@/util';

export const getTourRequests = async (
  currentPage: number,
  role: Roles,
  propertyId?: string
) => {
  const url = createTourRequestURL(currentPage, role, propertyId);

  const res: Response = await fetch(url, {
    method: REQUEST_METHODS.GET,
    headers: {
      ...getNodeRequiredRequestHeaders(),
      ...getAuthorizationHeader(),
    },
    next: { tags: [getCacheKey('toursTable')] },
  });

  if (res.status === 404) {
    return {
      data: [],
      pages: 1,
      results: 0,
      totalDocs: 0,
    } as APIResponse<ToursDetailsType>;
  }
  if (!res.ok) {
    throw await getServerError(res);
  }
  return res.json() as Promise<APIResponse<ToursDetailsType>>;
};

and then in the server compeont you can use the helper function from data-lib

import React from 'react';

import ToursTable from '@/components/ui/ToursTable';
import { Roles } from '@/enums';
import { getTourRequests } from '@/server/data-lib';

export default async function TableWrapper({
  currentPage,
}: {
  currentPage: number;
}) {
  const tourRequests = await getTourRequests(currentPage, Roles.TENANT);

  return (
    <ToursTable
      currentPage={currentPage}
      data={tourRequests.data}
      totalDocs={tourRequests.totalDocs}
    />
  );
}

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật