<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Rakib Ahsan</title>
    <description>The latest articles on Forem by Rakib Ahsan (@rakahsan).</description>
    <link>https://forem.com/rakahsan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1362752%2Fa6978a80-1d52-4ff2-88cc-3c7b843c938e.jpeg</url>
      <title>Forem: Rakib Ahsan</title>
      <link>https://forem.com/rakahsan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/rakahsan"/>
    <language>en</language>
    <item>
      <title>Building a Robust Next.js Quiz App: My Journey</title>
      <dc:creator>Rakib Ahsan</dc:creator>
      <pubDate>Tue, 09 Jul 2024 17:17:35 +0000</pubDate>
      <link>https://forem.com/rakahsan/attach-jwt-with-fetch-for-next-js-14-server-action-2gi4</link>
      <guid>https://forem.com/rakahsan/attach-jwt-with-fetch-for-next-js-14-server-action-2gi4</guid>
      <description>&lt;p&gt;The Challenge&lt;br&gt;
Recently, I embarked on an exciting project: building a Next.js app with dynamic client-server interactions and static site generation. The initial implementation was seamless, especially with token-based authentication for the login page. Everything was running smoothly until my client threw in a new requirement—a feature to create a quiz app.&lt;/p&gt;

&lt;p&gt;This new feature demanded server-side rendering (SSR) to expose an API endpoint. The backend, built with Laravel, included authentication routes. The critical part was ensuring that the quiz questions were tailored to the user’s profile, requiring secure access to the authenticated user's data.&lt;/p&gt;

&lt;p&gt;The Roadblocks&lt;br&gt;
Token Access: The token needed for authentication was stored in local storage, inaccessible from the server side. Conversely, the client side couldn't use cookies.&lt;br&gt;
Data Transmission: Although server-side data can be passed to the client via props, my component structure didn't allow for this straightforward transmission.&lt;br&gt;
The Solution&lt;br&gt;
Innovation and a bit of clever engineering helped me overcome these obstacles. Here's how:&lt;/p&gt;

&lt;p&gt;Token in URL: By encoding the token as a URL parameter, I could access it server-side. This approach allowed me to retrieve the token and use it as a Bearer token in the header.&lt;br&gt;
Seamless Integration: This method was not only secure but also adaptable, working flawlessly for infinite loading scenarios via server actions.&lt;br&gt;
Final Thoughts&lt;br&gt;
This project was a rewarding challenge, showcasing the power of combining Next.js with Laravel for a robust, full-stack solution. The ability to seamlessly integrate SSR with token-based authentication opened new doors for secure and dynamic user interactions.&lt;/p&gt;

&lt;p&gt;Thanks for joining me on this journey! If you have any questions or need assistance with similar projects, don't hesitate to reach out.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Attach jwt with fetch for next js 14 server action</title>
      <dc:creator>Rakib Ahsan</dc:creator>
      <pubDate>Mon, 18 Mar 2024 16:21:06 +0000</pubDate>
      <link>https://forem.com/rakahsan/attach-jwt-with-fetch-for-next-js-14-server-action-3pf8</link>
      <guid>https://forem.com/rakahsan/attach-jwt-with-fetch-for-next-js-14-server-action-3pf8</guid>
      <description>&lt;p&gt;We're all aware of how crucial JWT is in preventing cross-site API actions. However, dealing with attaching and handling the token every time can become quite cumbersome. That's why I've taken the initiative to enhance the fetch function within Next.js 14. Let's delve into this modification and see how it streamlines our workflow!&lt;/p&gt;

&lt;p&gt;Let's create a new file for this updated fetch function and export it as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { cookies } from "next/headers";

const baseURL = process.env.NEXT_PUBLIC_BACKEND_URL;

export async function fetchWithAuth(
  url: string,
  options: RequestInit = {}
): Promise&amp;lt;any&amp;gt; {
  try {
    const token = getTokenFromCookie();

    const headers = new Headers(options.headers);

    if (token) {
      headers.set("Authorization", `Bearer ${token}`);
    }
    const response = await fetch(baseURL + url, { ...options, headers });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();

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

function getTokenFromCookie(): string | undefined {
  const cookieStore = cookies();
  const tokenAll = cookieStore.get("token");
  return tokenAll?.value;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When it comes to setting the JWT token from the backend, assuming I'm using Laravel for the API, and setting the cookie for the login route:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { unstable_noStore as noStore } from "next/cache";
export async function Login(data: { email: string; password: string }) {
  try {
    noStore();
    const res = await fetch(`${baseURL}/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        cache: "no-store",
      },
      body: JSON.stringify(data),
    });
    const responseData = await res.json();

    if (responseData.token) {
      cookies().set("token", responseData.token, {
        httpOnly: true,
        expires: new Date("2030-01-01"),
      });
    }

    return responseData;
  } catch (error) {
    console.error("Error:", error);
    throw error;
  }
}

// HttpOnly ensures security against cross-attack

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>"Cachec - no store" Bug Next Js 14</title>
      <dc:creator>Rakib Ahsan</dc:creator>
      <pubDate>Mon, 18 Mar 2024 16:04:29 +0000</pubDate>
      <link>https://forem.com/rakahsan/cachec-no-store-bug-next-js-14-4ngg</link>
      <guid>https://forem.com/rakahsan/cachec-no-store-bug-next-js-14-4ngg</guid>
      <description>&lt;p&gt;Recently, I attempted to log in using JWT authentication. However, I encountered an issue where, upon logging in and storing the JWT in a cookie, sometimes the system would return an outdated token. This proved to be problematic as I had already deleted the previous token.&lt;/p&gt;

&lt;p&gt;Despite employing techniques such as using a fetch request with no cache, I still encountered unsatisfactory results. Subsequently, I delved into their documentation further and explored potential solutions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;`export async function Login(data: { email: string; password: string }) {
  try {
    noStore();//this work as force dynamic and no store
    const res = await fetch(`${baseURL}/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        cache: "no-store",
      },
      body: JSON.stringify(data),
    });
    const responseData = await res.json();

    console.log(responseData);

    if (responseData.token) {
      cookies().set("token", responseData.token, {
        httpOnly: true,
        expires: new Date("2030-01-01"),
      });
    }

    return responseData;
  } catch (error) {
    console.error("Error:", error);
    throw error;
  }
}`
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;next js doc &lt;a href="https://nextjs.org/docs/app/api-reference/functions/unstable_noStore"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>react</category>
    </item>
  </channel>
</rss>
