<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Kkr's NetxJS-Blog]]></title><description><![CDATA[Kkr's NetxJS-Blog]]></description><link>https://kkr-netxjs-blog.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/69bd1a84b238fd45a3902110/2f3edc35-b423-4f8c-8fbf-8c97a5441648.jpg</url><title>Kkr&apos;s NetxJS-Blog</title><link>https://kkr-netxjs-blog.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Thu, 18 Jun 2026 02:59:20 GMT</lastBuildDate><atom:link href="https://kkr-netxjs-blog.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Next.js ~Server and Client Components~]]></title><description><![CDATA[By default, layouts and pages are Server Components, which lets you fetch data and render parts of your UI on the server, optionally cache the result, and stream it to the client. When you need intera]]></description><link>https://kkr-netxjs-blog.hashnode.dev/next-js-server-and-client-components</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/next-js-server-and-client-components</guid><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Tue, 16 Jun 2026 21:55:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/40f767b0-1830-4821-9ae0-9fc26bfb6513.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>By default, layouts and pages are Server Components, which lets you fetch data and render parts of your UI on the server, optionally cache the result, and stream it to the client. When you need interactivity or browser APIs, you can use Client Components to layer in functionality.</p>
<p>Let me explain how Server and Client Components work in Next.js and when to use them, with examples of how to compose them together in your application.</p>
<p><strong>When to use Server and Client Components?</strong><br />The client and server environments have different capabilities. Server and client components allow you to run logic in each environment depending on your use case.</p>
<p>Use client Components when you need:</p>
<ul>
<li><p>Lifecycle logic. E.g. <code>useEffect</code>.</p>
</li>
<li><p>State and event handlers. E.g. <code>onClick</code>, <code>onChange</code>.</p>
</li>
<li><p>Browser-only APIs. E.g. <code>localStorage</code>, <code>window</code>, <code>navogator.geolocation</code><br />, etc.</p>
</li>
<li><p>Custom hooks.</p>
</li>
</ul>
<p>Use Server Components when you need:</p>
<ul>
<li><p>Fetch data from databases or APIs close to the source.</p>
</li>
<li><p>Use API keys, tokens, and other secrets without exposing them to the client.</p>
</li>
<li><p>Reduce the amount of JavaScript sent to the browser.</p>
</li>
<li><p>Improve the First Contentful Paint(FCP) and stream content progressively to the client</p>
</li>
</ul>
<p>For example, the <code>&lt;Page/&gt;</code> component is a Server Component that fetches data about a post and passes it as props to the <code>&lt;LinkButton/&gt;</code>, which handles client-side interactivity.</p>
<pre><code class="language-typescript">import LikeButton from '@/app/ui/like-button'
import { getPost } from '@/lib/data'
 
export default async function Page({
  params,
}: {
  params: Promise&lt;{ id: string }&gt;
}) {
  const { id } = await params
  const post = await getPost(id)
 
  return (
    &lt;div&gt;
      &lt;main&gt;
        &lt;h1&gt;{post.title}&lt;/h1&gt;
        {/* ... */}
        &lt;LikeButton likes={post.likes} /&gt;
      &lt;/main&gt;
    &lt;/div&gt;
  )
}
</code></pre>
<pre><code class="language-typescript">'use client'
 
import { useState } from 'react'
 
export default function LikeButton({ likes }: { likes: number }) {
  // ...
}
</code></pre>
<p><strong>How do Server and Client Components work in Next.js?</strong></p>
<p>On the server</p>
<p>On the server, Next.js uses React's APIs to orchestrate rendering. The rendering work is split into chunks by individual route segments (layouts and pages):</p>
<ul>
<li><p>Server Components are rendered into a special data format called the React Server Component Payload(RSC Payload).</p>
</li>
<li><p>Client Components and the RSC payload are used to prerender HTML.</p>
</li>
</ul>
<p><strong>What is the React Server Component Payload (RSC)?</strong></p>
<p>The RSC Payload is a compact binary representation of the rendered React Server Components tree. It's used by React on the client to update the browser's DOM. The RSC Payload contains:</p>
<ul>
<li><p>The rendered result of Server Components</p>
</li>
<li><p>Placeholders for where Client Components should be rendered and references to their JavaScript files</p>
</li>
<li><p>Any props passed from a Server Component to a Client Component</p>
</li>
</ul>
<p>On the client(first load)</p>
<ol>
<li><p>HTML is used to immediately show a fast, non-interactive preview of the route to the user.</p>
</li>
<li><p>RSC Payload is used to reconcile the Client and Server Component trees.</p>
</li>
<li><p>JavaScript is used to hydrate Client Components and make the application interactive.</p>
</li>
</ol>
<p><strong>What is hydration?</strong></p>
<p>Hydration is React's process for attaching <a href="https://react.dev/learn/responding-to-events">event handlers</a> to the DOM, to make the static HTML interactive.</p>
]]></content:encoded></item><item><title><![CDATA[Next.js ~What is the React Server Component (RSC) Payload~]]></title><description><![CDATA[The React Server Component is a specialized, compact binary data format used by Next.js to transfer the rendered result of Server Components from the server to the client.
What is inside the RSC Paylo]]></description><link>https://kkr-netxjs-blog.hashnode.dev/next-js-what-is-the-react-server-component-rsc-payload</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/next-js-what-is-the-react-server-component-rsc-payload</guid><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Thu, 04 Jun 2026 01:13:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/254bd520-7e06-4a2d-af97-3a60f0429d16.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The <strong>React Server Component</strong> is a specialized, compact binary data format used by Next.js to transfer the rendered result of Server Components from the server to the client.</p>
<p><strong>What is inside the RSC Payload?</strong></p>
<p>The payload contains the necessary information for the client to reconstruction the React component tree and update the DOM without needing to download or execute the original server Component JavaScript. Key contents include:</p>
<ul>
<li><p><strong>Rendered Output</strong>: The final UI structure (Virtual DOM) of your Server Components</p>
</li>
<li><p><strong>Client Component References</strong>: Pointers to the specific JavaScript files needed to hydrate those Client Components.</p>
</li>
<li><p><strong>Client Component References</strong>: Pointers to the specific JavaScript files needed to hydrate those Client Components.</p>
</li>
<li><p><strong>Serialized Props</strong>: Any data passed from a Server Component to a Client Component as props.</p>
</li>
<li><p><strong>Suspense Information</strong>: Metadata for streaming content in chunks as it becomes ready.</p>
</li>
</ul>
<p><strong>How Next.js Uses It</strong></p>
<ol>
<li><p><strong>On the Server</strong>: React renders Server Components into the RSC Payload. For the initial page load, Next.js uses this payload to generate the static HTML for a fast first paint.</p>
</li>
<li><p><strong>On the Client</strong>: For subsequent navigations (e.g., using <code>next/link</code>), only the RSC Payload is sent to the browser. React then use this payload to <a href="https://vercel.com/kb/guide/how-to-optimize-rsc-payload-size"><strong>reconcile the DOM</strong></a> and hydrate Client Components, making the page interactive</p>
</li>
</ol>
<p><strong>How to View It</strong></p>
<p>You can inspect the payload in your browser's developer tools:</p>
<ol>
<li><p>Open the <strong>Network</strong> tab.</p>
</li>
<li><p>Filter for requests with the content type <code>text/x-component</code>.</p>
</li>
<li><p>Click on a request to see the raw serialized React tree data.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Next.js ~Meta data~]]></title><description><![CDATA[Next.js(App Router) generates metadata that can be used for SEO or SNS sharing by exporting a meta object or generateMetadata functionality from layout.tsx or page.tsx.Unlike the traditional pages dir]]></description><link>https://kkr-netxjs-blog.hashnode.dev/next-js-meta-data</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/next-js-meta-data</guid><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Wed, 27 May 2026 08:52:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/a4282143-4057-4cdf-9e19-8776272cbd6d.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Next.js(App Router) generates metadata that can be used for SEO or SNS sharing by exporting a meta object or generateMetadata functionality from layout.tsx or page.tsx.<br />Unlike the traditional <code>pages</code> directory (next/head), everything is handled securely on the server-side. We’ll explain the main configuration patterns and provide clear examples.</p>
<ol>
<li>Static Metadata: To set a fixed title or description, export the Metadata object.</li>
</ol>
<pre><code class="language-typescript">// app/page.tsx or app/layout.tsx
import { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'Home | My Site',
  description: "This is the site's homepage.",
  keywords: ['Next.js', 'React', 'metadata'],
  openGraph: {
    title: 'Home | My Site',
    description: "This is the site's homepage.",
    url: 'https://example.com',
    siteName: 'My Site',
    images: [
      {
        url: 'https://example.com',
        width: 1200,
        height: 630,
      },
    ],
    locale: 'ja_JP',
    type: 'website',
  },
  twitter: {
    card: 'summary_large_image',
    title: 'Home | My Site',
    description: "This is the site's homepage.",
    images: ['https://example.com'],
  },
}

export default function Page() {
  return &lt;h1&gt;Hello!&lt;/h1&gt;
}
</code></pre>
<p>2. Dynamic Metadata: If you wish to modify metadata based on URL parameters (params) or data from external APIs—for example, on blog post pages—use the <code>generateMetadata</code> function.</p>
<pre><code class="language-typescript">// app/posts/[id]/page.tsx
import { Metadata } from 'next'

type Props = {
  params: Promise&lt;{ id: string }&gt;
}

// Data retrieval function (as Next.js automatically memoises this, calling it again on the page will not affect performance)
async function getPost(id: string) {
  const res = await fetch(`https://example.com{id}`)
  return res.json()
}

export async function generateMetadata({ params }: Props): Promise&lt;Metadata&gt; {
  const id = (await params).id
  const post = await getPost(id)

  return {
    title: `${post.title} | マイサイト`,
    description: post.summary,
    openGraph: {
      title: post.title,
      description: post.summary,
      images: [post.coverImage],
    },
  }
}

export default async function Page({ params }: Props) {
  const id = (await params).id
  const post = await getPost(id)
  
  return &lt;article&gt;&lt;h1&gt;{post.title}&lt;/h1&gt;&lt;/article&gt;
}
</code></pre>
<p>3.By defining a template in the root <code>layout.tsx</code> file using the title template feature (<code>title.template</code>), you can partially replace the title on subpages.</p>
<pre><code class="language-typescript">
// app/layout.tsx (root layout)
export const metadata: Metadata = {
  title: {
    template: '%s | MySite',
    default: 'MySite - Official Home', // Default used when a child page has no title
  },
}
</code></pre>
<pre><code class="language-typescript">// app/about/page.tsx (Company overview page)
export const metadata: Metadata = {
  title: 'Company Overview', // In the browser this will appear as "Company Overview | MySite"
}
</code></pre>
<p><strong>4. File based meta data</strong></p>
<p>Instead of writing the code yourself, simply place the files in a specific folder within the <code>app</code> directory, and Next.js will automatically recognise and generate the meta tags for you.</p>
<ul>
<li><p><strong>Icons</strong>: <code>favicon.ico</code>（root directory only）、<code>icon.png</code>、<code>apple-icon.png</code></p>
</li>
<li><p>Social media sharing images: <code>opengraph-image.png</code>、<code>twitter-image.png</code></p>
</li>
<li><p>For search engine crawlers: <code>robots.txt</code>、<code>sitemap.xml</code></p>
</li>
</ul>
<blockquote>
<p>💡 Note (Important) Exporting metadata via code (metadata / generateMetadata) is supported only in server components. Since it cannot be exported from client component files that declare “use client,” please define it in the parent layout or page (on the server side) in such cases.</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Next.js ~cache~]]></title><description><![CDATA[The cache in Next.js is a system that improves the performance of rendering results and data requests.
The latest versions of Next.js (Next.js 15, 16) have shifted from automatically caching everythin]]></description><link>https://kkr-netxjs-blog.hashnode.dev/next-js-cache</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/next-js-cache</guid><category><![CDATA[Next.js]]></category><category><![CDATA[cache]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Tue, 19 May 2026 21:57:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/2e8e2f58-ff08-46e8-b715-23c7ff0d06be.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The cache in Next.js is a system that improves the performance of rendering results and data requests.</p>
<p>The latest versions of Next.js (Next.js 15, 16) have shifted from automatically caching everything to making caching developer-directed.</p>
<p><strong>Main cache features (App Router)</strong></p>
<p>Next.js has four independent caching layers between the server and the client.</p>
<table>
<thead>
<tr>
<th><strong>Cache name</strong></th>
<th><strong>Stored items</strong></th>
<th><strong>Location</strong></th>
<th><strong>Purpose</strong></th>
<th><strong>Expiration</strong></th>
</tr>
</thead>
<tbody><tr>
<td><strong>Request Memoization</strong></td>
<td>API responses</td>
<td>Server</td>
<td>Reuse data within the same component tree</td>
<td>Only within a single request</td>
</tr>
<tr>
<td><strong>Data Cache</strong></td>
<td>API responses / data</td>
<td>Server</td>
<td>Persist data across users and deployments</td>
<td>Persistent (can be manually refreshed)</td>
</tr>
<tr>
<td><strong>Full Route Cache</strong></td>
<td>HTML / RSC payload</td>
<td>Server</td>
<td>Reduce rendering cost</td>
<td>Persistent (can be manually refreshed)</td>
</tr>
<tr>
<td><strong>Router Cache</strong></td>
<td>RSC payload</td>
<td>Browser</td>
<td>Reduce requests during navigation</td>
<td>For the session (seconds to minutes)</td>
</tr>
</tbody></table>
<hr />
<p><strong>Latest cache control:</strong> <code>use cache</code> <a href="https://www.youtube.com/watch?v=jK8NLWZIUfA">[1]</a></p>
<p>In <a href="https://nextjs.org/blog/composable-caching"><strong>Next.js 15/16</strong></a>, the new <code>use cache</code> directive was introduced. This allows intuitive caching to be specified at the level of functions or components. [<a href="https://zenn.dev/akfm/articles/nextjs-caching-history">1</a>, <a href="https://azukiazusa.dev/blog/cache-control-with-use-cache-directive-in-nextjs/">2</a>, <a href="https://www.youtube.com/watch?v=jK8NLWZIUfA">3</a>]</p>
<ol>
<li><p><strong>Data-level caching</strong>: Cache specific data-fetching functions.</p>
<pre><code class="language-typescript">export async function getProducts() {
  'use cache' // この関数をキャッシュする
  const data = await db.query('...')
  return data
}
</code></pre>
</li>
<li><p><strong>UI-level caching</strong>: Cache the rendered output of an entire component.</p>
<pre><code class="language-typescript">async function HeavyComponent() {
  'use cache'
  return &lt;div&gt;重い処理の結果&lt;/div&gt;
</code></pre>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Next.js ~streaming~]]></title><description><![CDATA[Streaming is a data transfer technique that allows you to break down a route into smaller "chunks" and progressively stream them from t he server to the client as they become ready.


By stream, you c]]></description><link>https://kkr-netxjs-blog.hashnode.dev/next-js-streaming</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/next-js-streaming</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Performance Optimization]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Sun, 10 May 2026 22:45:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/f1eb8d15-e2c4-4707-8aa4-37c544d98248.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Streaming is a data transfer technique that allows you to break down a route into smaller "chunks" and progressively stream them from t he server to the client as they become ready.</p>
<img src="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/4ebcd73a-22e8-4cef-9dbe-726a2e2605d8.jpg" alt="" style="display:block;margin:0 auto" />

<p>By stream, you can prevent slow data requests from blocking your whole page. This allows the user to see and interact with parts of the page without waiting for all the data to load before any UI can be shown to the user.</p>
<p>Streaming works well with React's component model, as each component can be considered a chunk.</p>
<p>There are two ways you implement streaming in Next.js:<br />1. At the page level, with the <code>loading.ts</code> file(which creates <code>&lt;Suspense&gt;</code> for you</p>
<p>2. At the component level, with <code>&lt;Suspense&gt;</code> for more granular control.</p>
<p>**Streaming a whole page with `loading.tsx` **</p>
<p>In the `/app/dashboard` folder, create a new file called `loading.tsx`:</p>
<pre><code class="language-typescript">export default function Loading() {
  return &lt;div&gt;Loading...&lt;/div&gt;;
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/8cf6361b-be21-4c23-a5f9-988b041bec6a.jpg" alt="" style="display:block;margin:0 auto" />

<p>A few things are happening here:</p>
<ol>
<li><p><code>loading.tsx</code> is a special Next.js file built on top of React Suspense. It allows you to create fallback UI to show as a replacement while page content loads.</p>
</li>
<li><p>Since <code>&lt;SideNav&gt;</code> is static, it's shown immediately. The user can interact with <code>&lt;SideNav&gt;</code> while the dynamic content is loading.</p>
</li>
<li><p>The user doesn't have to wait for the page to finish loading before navigating away (this is called interruptable navigation).</p>
</li>
</ol>
<p>Congratulations! You've just implemented streaming. But we can do more to improve the user experience. Let's show a loading skeleton instead of the <code>Loading…</code> text.</p>
<p>**Adding loading skeltons**</p>
<p>A loading skeleton is a simplified version of the UI. Many websites use them as a placeholder(or fallback) to indicate to users that the content is loading. Any UI you add in <code>loading.tsx</code> will be embedded as part of a static file, and sent first. Then, the rest of the dynamic content will be streamed from the server to the client.</p>
<p>Inside your <code>loading.tsx</code> file, import a new component called <code>&lt;DashboardSkeleton&gt;</code>:</p>
<pre><code class="language-typescript">import DashboardSkeleton from '@/app/ui/skeletons';
 
export default function Loading() {
  return &lt;DashboardSkeleton /&gt;;
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/e15eeb37-79c3-4c1d-935c-38804dab120a.jpg" alt="" style="display:block;margin:0 auto" />

<p>**Fixing the loading skeleton bug with route groups**<br />Right now, your loading skeleton will apply to the invoices.</p>
<p>Since <code>loading.tsx</code> is a level higher than <code>/invoices/page.tsx</code> and <code>/customers/page.tsx</code> in the file system, it's also applied to those pages.</p>
<p>We can change this with <a href="https://nextjs.org/docs/app/building-your-application/routing/route-groups">Route Groups</a>. Create a new folder called <code>/(overview)</code> inside the dashboard folder. Then, move your <code>loading.tsx</code> and <code>page.tsx</code> files inside the folder:</p>
<img src="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/66398c76-0ba9-45ab-9333-fbdb8204d59b.jpg" alt="" style="display:block;margin:0 auto" />

<p>Now, the <code>loading.tsx</code> file will only apply to your dashboard overview page.</p>
<p>Route groups allow you to organize files into logical groups without affecting the URL path structure. When you create a new folder using parentheses <code>()</code>, the name won't be included in the URL path. So <code>/dashboard/(overview)/page.tsx</code> becomes <code>/dashboard</code>.</p>
<p>Here, you're using a route group to ensure <code>loading.tsx</code> only applies to your dashboard overview page. However, you can also use route groups to separate your application into sections (e.g. <code>(marketing)</code> routes and <code>(shop)</code> routes) or by teams for larger applications.</p>
<p>**Streaming a component**</p>
<p>So far, you're streaming a whole page. But you can also be more granular and stream specific components using React Suspense.</p>
<p>Suspense allows you to defer reading parts of your application until some condition is met. You can wrap your dynamic components in Suspense. Then, pass it a fallback component to show while the dynamic component loads.</p>
<p>If you remember the slow data request, <code>fetchRevenue()</code>, this is the request that is slowing down the whole page. Instead of blocking your whole page, you can use Suspense to stream only this component and immediately show the rest of the page's UI.</p>
<p>To do so, you'll need to move the data fetch to the component, let's update the code to see what that'll look like:</p>
<p>Delete all instances of <code>fetchRevenue()</code> and its data from <code>/dashboard/(overview)/page.tsx</code>:</p>
<pre><code class="language-typescript">import { Card } from '@/app/ui/dashboard/cards';
import RevenueChart from '@/app/ui/dashboard/revenue-chart';
import LatestInvoices from '@/app/ui/dashboard/latest-invoices';
import { lusitana } from '@/app/ui/fonts';
import { fetchLatestInvoices, fetchCardData } from '@/app/lib/data'; // remove fetchRevenue
 
export default async function Page() {
  const revenue = await fetchRevenue() // delete this line
  const latestInvoices = await fetchLatestInvoices();
  const {
    numberOfInvoices,
    numberOfCustomers,
    totalPaidInvoices,
    totalPendingInvoices,
  } = await fetchCardData();
 
  return (
    // ...
  );
}
</code></pre>
<p>Then, import <code>&lt;Suspense&gt;</code> from React, and wrap it around <code>&lt;RevenueChart /&gt;</code>. You can pass it a fallback component called <code>&lt;RevenueChartSkeleton&gt;</code>.</p>
<pre><code class="language-typescript">import { Card } from '@/app/ui/dashboard/cards';
import RevenueChart from '@/app/ui/dashboard/revenue-chart';
import LatestInvoices from '@/app/ui/dashboard/latest-invoices';
import { lusitana } from '@/app/ui/fonts';
import { fetchLatestInvoices, fetchCardData } from '@/app/lib/data';
import { Suspense } from 'react';
import { RevenueChartSkeleton } from '@/app/ui/skeletons';
 
export default async function Page() {
  const latestInvoices = await fetchLatestInvoices();
  const {
    numberOfInvoices,
    numberOfCustomers,
    totalPaidInvoices,
    totalPendingInvoices,
  } = await fetchCardData();
 
  return (
    &lt;main&gt;
      &lt;h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}&gt;
        Dashboard
      &lt;/h1&gt;
      &lt;div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4"&gt;
        &lt;Card title="Collected" value={totalPaidInvoices} type="collected" /&gt;
        &lt;Card title="Pending" value={totalPendingInvoices} type="pending" /&gt;
        &lt;Card title="Total Invoices" value={numberOfInvoices} type="invoices" /&gt;
        &lt;Card
          title="Total Customers"
          value={numberOfCustomers}
          type="customers"
        /&gt;
      &lt;/div&gt;
      &lt;div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8"&gt;
        &lt;Suspense fallback={&lt;RevenueChartSkeleton /&gt;}&gt;
          &lt;RevenueChart /&gt;
        &lt;/Suspense&gt;
        &lt;LatestInvoices latestInvoices={latestInvoices} /&gt;
      &lt;/div&gt;
    &lt;/main&gt;
  );
}
</code></pre>
<p>Finally, update the <code>&lt;RevenueChart&gt;</code> component to fetch its own data and remove the prop passed to it:</p>
<pre><code class="language-typescript">import { generateYAxis } from '@/app/lib/utils';
import { CalendarIcon } from '@heroicons/react/24/outline';
import { lusitana } from '@/app/ui/fonts';
import { fetchRevenue } from '@/app/lib/data';
 
// ...
 
export default async function RevenueChart() { // Make component async, remove the props
  const revenue = await fetchRevenue(); // Fetch data inside the component
 
  const chartHeight = 350;
  const { yAxisLabels, topLabel } = generateYAxis(revenue);
 
  if (!revenue || revenue.length === 0) {
    return &lt;p className="mt-4 text-gray-400"&gt;No data available.&lt;/p&gt;;
  }
 
  return (
    // ...
  );
}
 
</code></pre>
<p>Now refresh the page, you should see the dashboard information almost immediately, while a fallback skeleton is shown for <code>&lt;RevenueChart&gt;</code>:</p>
<img src="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/3e382600-62e9-422e-8bcd-45016d319647.jpg" alt="" style="display:block;margin:0 auto" />

<p>**Practice: Streaming** <code>&lt;LatestInvoices&gt;</code></p>
<p>Now it's your turn! Practice what you've just learned by streaming the <code>&lt;LatestInvoices&gt;</code> component.</p>
<p>Move <code>fetchLatestInvoices()</code> down from the page to the <code>&lt;LatestInvoices&gt;</code> component. Wrap the component in a <code>&lt;Suspense&gt;</code> boundary with a fallback called <code>&lt;LatestInvoicesSkeleton&gt;</code>.</p>
<p>Once you're ready, expand the toggle to see the solution code:</p>
<pre><code class="language-typescript">import { Card } from '@/app/ui/dashboard/cards';
import RevenueChart from '@/app/ui/dashboard/revenue-chart';
import LatestInvoices from '@/app/ui/dashboard/latest-invoices';
import { lusitana } from '@/app/ui/fonts';
import { fetchCardData } from '@/app/lib/data'; // Remove fetchLatestInvoices
import { Suspense } from 'react';
import {
  RevenueChartSkeleton,
  LatestInvoicesSkeleton,
} from '@/app/ui/skeletons';
 
export default async function Page() {
  // Remove `const latestInvoices = await fetchLatestInvoices()`
  const {
    numberOfInvoices,
    numberOfCustomers,
    totalPaidInvoices,
    totalPendingInvoices,
  } = await fetchCardData();
 
  return (
    &lt;main&gt;
      &lt;h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}&gt;
        Dashboard
      &lt;/h1&gt;
      &lt;div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4"&gt;
        &lt;Card title="Collected" value={totalPaidInvoices} type="collected" /&gt;
        &lt;Card title="Pending" value={totalPendingInvoices} type="pending" /&gt;
        &lt;Card title="Total Invoices" value={numberOfInvoices} type="invoices" /&gt;
        &lt;Card
          title="Total Customers"
          value={numberOfCustomers}
          type="customers"
        /&gt;
      &lt;/div&gt;
      &lt;div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8"&gt;
        &lt;Suspense fallback={&lt;RevenueChartSkeleton /&gt;}&gt;
          &lt;RevenueChart /&gt;
        &lt;/Suspense&gt;
        &lt;Suspense fallback={&lt;LatestInvoicesSkeleton /&gt;}&gt;
          &lt;LatestInvoices /&gt;
        &lt;/Suspense&gt;
      &lt;/div&gt;
    &lt;/main&gt;
  );
}
</code></pre>
<p>**<strong>Grouping components</strong>**<br />To create more of a staggered effect, you can group the cards using a wrapper component. This means the static <code>&lt;SideNav/&gt;</code> will be shown first, followed by the cards, etc.  </p>
<p>In your <code>page.tsx</code> file:</p>
<ol>
<li><p>Delete your <code>&lt;Card&gt;</code> components.</p>
</li>
<li><p>Delete the <code>fetchCardData()</code> function.</p>
</li>
<li><p>Import a new <strong>wrapper</strong> component called <code>&lt;CardWrapper /&gt;</code>.</p>
</li>
<li><p>Import a new <strong>skeleton</strong> component called <code>&lt;CardsSkeleton /&gt;</code>.</p>
</li>
<li><p>Wrap <code>&lt;CardWrapper /&gt;</code> in Suspense.</p>
</li>
</ol>
<pre><code class="language-typescript">import CardWrapper from '@/app/ui/dashboard/cards';
// ...
import {
  RevenueChartSkeleton,
  LatestInvoicesSkeleton,
  CardsSkeleton,
} from '@/app/ui/skeletons';
 
export default async function Page() {
  return (
    &lt;main&gt;
      &lt;h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}&gt;
        Dashboard
      &lt;/h1&gt;
      &lt;div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4"&gt;
        &lt;Suspense fallback={&lt;CardsSkeleton /&gt;}&gt;
          &lt;CardWrapper /&gt;
        &lt;/Suspense&gt;
      &lt;/div&gt;
      // ...
    &lt;/main&gt;
  );
}
</code></pre>
<p>Then, move into the file <code>/app/ui/dashboard/cards.tsx</code>, import the <code>fetchCardData()</code> function, and invoke it inside the <code>&lt;CardWrapper/&gt;</code> component. Make sure to uncomment any necessary code in this component.</p>
<pre><code class="language-typescript">// ...
import { fetchCardData } from '@/app/lib/data';
 
// ...
 
export default async function CardWrapper() {
  const {
    numberOfInvoices,
    numberOfCustomers,
    totalPaidInvoices,
    totalPendingInvoices,
  } = await fetchCardData();
 
  return (
    &lt;&gt;
      &lt;Card title="Collected" value={totalPaidInvoices} type="collected" /&gt;
      &lt;Card title="Pending" value={totalPendingInvoices} type="pending" /&gt;
      &lt;Card title="Total Invoices" value={numberOfInvoices} type="invoices" /&gt;
      &lt;Card
        title="Total Customers"
        value={numberOfCustomers}
        type="customers"
      /&gt;
    &lt;/&gt;
  );
}
</code></pre>
<p>Refresh the page, and you should see all the cards load in at the same time. You can use this pattern when you want multiple components to load in at the same time.  </p>
<p><strong>Deciding where to place your Suspense boundaries</strong></p>
<p>Where you place your Suspense boundaries will depend on a few things:</p>
<ol>
<li><p>How you want the user to experience the page as it streams.</p>
</li>
<li><p>What content you want to prioritize.</p>
</li>
<li><p>If the components rely on data fetching.</p>
</li>
</ol>
<p>Take a look at your dashboard page, is there anything you would've done differently?</p>
<p>Don't worry. There isn't a right answer.</p>
<ul>
<li><p>You could stream the <strong>whole page</strong> like we did with <code>loading.tsx</code>... but that may lead to a longer loading time if one of the components has a slow data fetch.</p>
</li>
<li><p>You could stream <strong>every component</strong> individually... but that may lead to UI <em>popping</em> into the screen as it becomes ready.</p>
</li>
<li><p>You could also create a <em>staggered</em> effect by streaming <strong>page sections</strong>. But you'll need to create wrapper components.</p>
</li>
</ul>
<p>Where you place your suspense boundaries will vary depending on your application. In general, it's good practice to move your data fetches down to the components that need it, and then wrap those components in Suspense. But there is nothing wrong with streaming the sections or the whole page if that's what your application needs.</p>
<p>Don't be afraid to experiment with Suspense and see what works best, it's a powerful API that can help you create more delightful user experiences.</p>
]]></content:encoded></item><item><title><![CDATA[Next.js ~Chache~]]></title><description><![CDATA[In Next.js, there are four layers of caching strategy for performance optimization or cutting costs.



Cache Type
Storage Location
Stored Content
Purpose
Lifetime



Request Memoization
Server
fetch ]]></description><link>https://kkr-netxjs-blog.hashnode.dev/next-js-chache</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/next-js-chache</guid><category><![CDATA[Next.js]]></category><category><![CDATA[cache]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Wed, 29 Apr 2026 23:02:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/ec0a5334-9476-4150-af89-c1887e2a2326.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Next.js, there are four layers of caching strategy for performance optimization or cutting costs.</p>
<table>
<thead>
<tr>
<th>Cache Type</th>
<th>Storage Location</th>
<th>Stored Content</th>
<th>Purpose</th>
<th>Lifetime</th>
</tr>
</thead>
<tbody><tr>
<td>Request Memoization</td>
<td>Server</td>
<td><code>fetch</code> response values</td>
<td>Avoid duplicate requests within a render pass</td>
<td>Per request only</td>
</tr>
<tr>
<td>Data Cache</td>
<td>Server</td>
<td>Data</td>
<td>Reuse data across users and deployments</td>
<td>Persistent (revalidatable)</td>
</tr>
<tr>
<td>Full Route Cache</td>
<td>Server</td>
<td>HTML / RSC payload</td>
<td>Reduce rendering cost</td>
<td>Persistent (revalidatable)</td>
</tr>
<tr>
<td>Router Cache</td>
<td>Client</td>
<td>RSC payload</td>
<td>Reduce requests during client-side navigation</td>
<td>Session-based / time-limited</td>
</tr>
</tbody></table>
<p>Next.js 15 introduced <code>use cache</code> directive.</p>
<p>・This is a new mechanism that allows you to declare “cache this output” on a per-function or per-component basis.</p>
<p>・You can intuitively specify the scope of caching without using complex APIs such as the traditional <code>unstable_cache</code>.</p>
<p>・Next.js 16 introduced PPR(Partial Pre Rendering), which enhances the mechanism for delivering content quickly by combining cached static content with dynamic content.  </p>
<p>Cache Refresh (Revalidation) There are two main ways to refresh cached data.</p>
<p>Time-based Revalidation: Specify the number of seconds using the <code>next: { revalidate: 60 }</code> option in the <code>fetch</code> request.</p>
<p>On-demand Revalidation: Use <code>revalidatePath</code> or <code>revalidateTag</code> to explicitly invalidate the cache when a data mutation occurs.</p>
]]></content:encoded></item><item><title><![CDATA[NextJS ~Authentication~]]></title><description><![CDATA[Auth.js is the open source library that add authentication feature such as login.  
**Main features are follows:**
・Many authentications: OAuth provider such as Google, Github, Twitter, also support m]]></description><link>https://kkr-netxjs-blog.hashnode.dev/nextjs-authentication</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/nextjs-authentication</guid><category><![CDATA[Next.js]]></category><category><![CDATA[authentication]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Wed, 29 Apr 2026 00:30:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/71e94068-c8c2-42f2-b1c9-5de6b3f8fef4.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Auth.js is the open source library that add authentication feature such as login.  </p>
<p>**Main features are follows:**</p>
<p>・Many authentications: OAuth provider such as Google, Github, Twitter, also support main(majic link) and ID/pasword authentication.  </p>
<p>・Next.js Optimization: Designed to integrate seamlessly with Next.js API routes and server components, enabling efficient security and session management.</p>
<p>・Flexible Data Management: By using database adapters, you can manage user information and sessions in your own database (MySQL, PostgreSQL, MongoDB, etc.).  </p>
<p>・Latest Auth.js (v5): Starting with the latest v5 series, it has evolved into a comprehensive authentication library called “Auth.js” that supports not only Next.js but also other frameworks such as SvelteKit and SolidStart.  </p>
<p>**Benefits of Implementation **<br />Building an authentication system from scratch requires a tremendous amount of time to implement security measures and adapt to specification changes from various providers. With NextAuth.js, you can implement a secure authentication flow with just a few lines of configuration, significantly improving development efficiency.</p>
]]></content:encoded></item><item><title><![CDATA[NextJS  ~Edge Runtime~]]></title><description><![CDATA[Even though Next.js runs on Node.js, do you know that middleware runs on Edge Runtime?
I introduce you follows:・ What is Edge Runtime?・ What is the difference for Node.js Runtime?・ Can you use Node.js]]></description><link>https://kkr-netxjs-blog.hashnode.dev/nextjs-edge-runtime</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/nextjs-edge-runtime</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Middleware]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Thu, 23 Apr 2026 07:19:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/f50165a5-c0d2-446c-acde-5527c6541616.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Even though Next.js runs on Node.js, do you know that middleware runs on Edge Runtime?</p>
<p>I introduce you follows:<br />・ What is Edge Runtime?<br />・ What is the difference for Node.js Runtime?<br />・ Can you use Node.js on Runtime?</p>
<p>**The role of middleware**<br />Middleware, as the name suggests, is a mechanism that processes requests between the client and server. Examples of the purposes for which middleware can be used include:</p>
<ul>
<li><p>redirecting to the login screen when accessing the login URL before authentication;</p>
</li>
<li><p>capturing the request data and logging it;</p>
</li>
<li><p>changing the path for each request for A/B testing purposes and returning it.</p>
</li>
</ul>
<p>For more specific examples, please refer to the Next.js official documentation.</p>
<p>**What is Edge Runtime ?**<br />Next.js middleware runs on Edge Runtime. Edge runtime is the environment in which JavaScript runs with limited functionalities.</p>
<p>Edge Runtime adapts the V8 engine and supports Web APIs such as <code>fetch, Request</code>, and <code>Response</code> .</p>
<p>While it doesn't support Node.js native APIs such as ` fs `, ` http `, and `crypto.`</p>
<p>Therefore, if you need to encrypt authentication credentials within the middleware or access the file system, you cannot use Node.js APIs and must instead consider alternative approaches, such as using external modules or moving the functionality to the application layer. For details on supported APIs, please refer to the Edge Runtime chapter in the official documentation.</p>
<p>Edge Runtime is designed for using edge computing and has been optimized for lightweight performance by carefully selecting only the necessary features.</p>
<p>Edge computing includes:</p>
<ul>
<li><p>Vercel Edge Functions</p>
</li>
<li><p>AWS Lambda<a href="https://hashnode.com/@david264" class="user-mention" data-type="mention" title="EDGE">EDGE</a></p>
</li>
<li><p>Cloudflare Workers</p>
</li>
</ul>
<p>Most of them are limited by the size of memory or code for optimization performance. For example, Vercel is designed for a limitation of 1MB〜4MB code size or a response within 25s, which causes the timeout error.  </p>
<p>**In Next.js v15, we can use Node.js in middleware on runtime enviroment.**<br />We can use Node.js in middleware on runtime envoriment experimentally.<br />This allows us to use <code>fs</code> , <code>http</code> .  </p>
<p>**Points to Consider*<br />We can use Node.js's native APIs to add more complex features to the middleware. However, we must consider the impact on performance and resource consumption.  </p>
<p>**Keep middleware as simple as possible*<br />Middleware essentially works on requests or responses. We have to restrict jobs to simple tasks such as header manipulation and redirects, and move heavy work to the server. If we need to use the Node.js native API, use it.</p>
]]></content:encoded></item><item><title><![CDATA[NextJS  ~ Proxy ~]]></title><description><![CDATA[In Next.js, “Proxy” primarily refers to functionality that acts as middleware to forward (rewrite) API requests or insert processing steps before a request is completed. Notably, starting with Next.js]]></description><link>https://kkr-netxjs-blog.hashnode.dev/nextjs-proxy</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/nextjs-proxy</guid><category><![CDATA[Next.js]]></category><category><![CDATA[proxy]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Wed, 15 Apr 2026 06:14:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/f02574f0-641f-42f8-8147-43519698d1bc.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Next.js, “Proxy” primarily refers to functionality that acts as middleware to forward (rewrite) API requests or insert processing steps before a request is completed. Notably, starting with Next.js 16, the traditional ‘Middleware’ has been renamed to “Proxy.” The main implementation methods, tailored to specific use cases, are as follows:</p>
<ol>
<li>Request Forwarding and Rewriting (Rewrites) This is used to bypass cross-origin restrictions (CORS) in development environments or to proxy specific paths (e.g., /api/:path*) to an external backend server. Configure this in next.config.js.</li>
</ol>
<pre><code class="language-typescript">// next.config.ts
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'https://backend-api.com*',
      },
    ];
  },
};
</code></pre>
<ol>
<li>Proxy (formerly Middleware) in Next.js 16 and later Starting with Next.js 16, you can create a <code>proxy.ts</code> (or <code>proxy.js</code>) file in the project root to perform tasks such as authentication checks, logging, and header modifications before the request is completed.</li>
</ol>
<p>File name: proxy.ts or proxy.js Role: Executed before rendering; allows for redirects and response rewriting Note: The traditional middleware.ts is deprecated, and migration to proxy.ts is recommended.</p>
<pre><code class="language-typescript">//proxy.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function proxy(request: NextRequest) {
  // 認証チェックなどのロジック
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    // リダイレクトや書き換えの処理
    return NextResponse.rewrite(new URL('/login', request.url))
  }
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[NextJS API Routes]]></title><description><![CDATA[When you recieve a request in api route, you have to create right API.In NextJS, you deploy the `route.ts` file beneath the app/api foler.
GET /api/users
POST /api/users
GET /api/users/[id]
PUT /api/u]]></description><link>https://kkr-netxjs-blog.hashnode.dev/nextjs-api-routes</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/nextjs-api-routes</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Mon, 13 Apr 2026 23:54:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/f6f8c91b-c345-49ba-bccd-1580ed9c0466.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When you recieve a request in api route, you have to create right API.<br />In NextJS, you deploy the `<code>route.ts`</code> file beneath the <code>app/api</code> foler.</p>
<pre><code class="language-plaintext">GET /api/users
POST /api/users
GET /api/users/[id]
PUT /api/users/[id]
DELETE /api/users/[id]
</code></pre>
<p>You define the method in the file.</p>
<pre><code class="language-typescript">//app/api/users/route.ts
import { NextRequest, NextResponse } from "next/server";

export function GET(request: NextRequest): NextResponse {
    // GET /api/users request
}

export function POST(request: NextRequest): NextResponse {
    // POST /api/users request
}
</code></pre>
<pre><code class="language-typescript">//app/api/users/[id]/route.ts

import { NextRequest, NextResponse } from "next/server";

export function GET(request: NextRequest, { params }: { params: { id: string } }): NextResponse {
    // GET /api/users/[id] request
}

export function PUT(request: NextRequest, { params }: { params: { id: string } }): NextResponse {
    // PUT /api/users/[id] request
}

export function DELETE(request: NextRequest, { params }: { params: { id: string } }): NextResponse {
    // DELETE /api/users/[id] request
}
</code></pre>
<p>As a result, you can deal with each handling.</p>
<p>**Query Parameter**</p>
<pre><code class="language-typescript">// ...
//e.g）GET /api/users?query=hoge 
export function GET(request: NextRequest): NextResponse {
  const params = request.nextUrl.searchParams;
  const query = params.get("query");
  // query = "hoge"
// ...
</code></pre>
<p>**Request Body**</p>
<pre><code class="language-typescript">// ...
// e.g）POST /api/users (request body: {"key": "hoge"}) 
export async function POST(request: NextRequest): Promise&lt;NextResponse&gt; {
  const params = await request.json();
  // params = {key: "hoge"}
// ...
</code></pre>
<p><strong>Pass Parameter</strong></p>
<pre><code class="language-typescript">// ...
// 例）POST /api/users (request body: {"key": "hoge"}) 
export async function POST(request: NextRequest): Promise&lt;NextResponse&gt; {
  const params = await request.json();
  // params = {key: "hoge"}
// ...
</code></pre>
<p>If multiple parameters are included, add those of types to <code>param</code>.</p>
<pre><code class="language-typescript">// ...
// e.g) GET /api/users/hoge/items/1
export function GET(request: NextRequest, { params }: { params: { id: string, itemId: number } }): NextResponse {
    // params.id = "hoge"
    // params.itemId = 1
}
// ...
</code></pre>
<p>**CORS**<br />If you access the API from different domain, you can defind the CORS to share the souce.</p>
<pre><code class="language-typescript">export function GET(request: NextRequest): NextResponse {
    return NextResponse.json(
        { response: "Test response." },
        {
          status: 200,  // Status code
          headers: {    // Response header
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
          },
        },
  );
}
</code></pre>
<p>When defining the header in the response object, you can also define the CORS header. If there are too many endpoints, it is better to define the header in the middleware, because the header may become redundant.</p>
]]></content:encoded></item><item><title><![CDATA[API Routes ]]></title><description><![CDATA[Introduction | What Are API Routes? Why Use Them?

Next.js provides “API Routes” as a mechanism that allows you to implement backend-like processing beyond the scope of the frontend. Simply put, this ]]></description><link>https://kkr-netxjs-blog.hashnode.dev/api-routes</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/api-routes</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Sat, 11 Apr 2026 02:07:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/662f81f0-3c4c-49ef-9eb3-4df3675b4f1b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<ol>
<li><strong>Introduction | What Are API Routes? Why Use Them?</strong></li>
</ol>
<p>Next.js provides “API Routes” as a mechanism that allows you to implement backend-like processing beyond the scope of the frontend. Simply put, this is a feature that lets you define server-side processing (API endpoints) within Next.js.</p>
<p><strong>For example, it is used in the following scenarios:</strong></p>
<p>・Querying a database to retrieve and return data</p>
<p>・Receiving form submissions and sending emails or saving the data</p>
<p>・Acting as a server-side intermediary for communication with external APIs</p>
<p>・Processing and validating authentication tokens and cookies on the server</p>
<p><strong>This is particularly beneficial for developers who:</strong></p>
<p>・Are working as individuals or in small teams and prioritize speed</p>
<p>・Want to work efficiently without separating UI development from API implementation</p>
<p>・Want to handle the minimum implementation themselves, even with limited backend experience</p>
<p>Additionally, within the Next.js App Router configuration, you can define API routes in the same way by using the <code>app/api/</code> directory</p>
<p><strong>That said, many of you may have questions like the following:</strong></p>
<p>・Is it safe to use API Routes in production?</p>
<p>・What types of tasks are they best suited for?</p>
<p>・How do they differ from fetch and axios?</p>
<p>What’s the difference between the Pages Router and the App Router?</p>
<p>In this article, we’ll address these questions while introducing common patterns and best practices used in real-world scenarios.</p>
<p>2. Basic Syntax and Directory Structure of API Routes</p>
<p>Next.js API Routes provide a mechanism for defining server-side logic using simple syntax. They support both App Router and Pages Router configurations, and the syntax and placement differ slightly between the two.</p>
<p>✅Basic Syntax for Pages Router Configuration</p>
<p>In Pages Router, files placed under the <code>pages/api/</code> folder are automatically recognized as endpoints.</p>
<pre><code class="language-typescript">// pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ message: 'Hello API!' });
}
</code></pre>
<p>In this case, accessing /api/hello will return { message: “Hello API!” }.</p>
<p>You can use req.method to handle POST, GET, PUT, and other requests.</p>
<p>You can also handle database connections and session management within this code.</p>
<p>✅Basic Syntax for App Router Configuration (Next.js 13 and later)</p>
<p>In App Router, you must create files within the <code>app/api/</code> directory and export HTTP method functions (such as GET and POST) on a per-file basis.</p>
<pre><code class="language-typescript">// app/api/hello/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json({ message: 'Hello from App Router!'         });
}
</code></pre>
<p>In the App Router configuration, the key point is that the file name is <code>route.ts</code>. This allows Next.js to recognize this file as an API endpoint.</p>
<p>The supported methods are as follows:</p>
<p>GET()</p>
<p>POST(req: Request)</p>
<p>PUT()</p>
<p>DELETE()</p>
<p>PATCH()</p>
<p>If necessary, use the Request object to retrieve the request body as follows:</p>
<pre><code class="language-typescript">export async function POST(req: Request) {
  const body = await req.json();
  return NextResponse.json({ received: body });
}
</code></pre>
<p>📁 Example of folder structure (App Router)</p>
<pre><code class="language-plaintext">app/
  api/
    hello/
      route.ts         ← /api/hello
    contact/
      route.ts         ← /api/contact
</code></pre>
<p>🧩 Using with Middleware</p>
<p>API Routes can be combined with Next.js middleware (middleware.ts) and functions like <code>headers()</code> to enable advanced control features such as token authentication and redirect management.</p>
<p>① Form Submission Processing (e.g., Contact Form)</p>
<p>For example, when creating a “contact form,” the basic process involves sending and processing the information entered by the user via an API route.</p>
<p>✅ Benefits</p>
<p>Validation and submission processing can be separated from the front end</p>
<p>Flexible implementation of anti-spam measures and authentication logic</p>
<p>🔒 ② Secure authentication and authorization (JWT and session management)</p>
<p>For authentication, we may integrate with external services such as Firebase Authentication or Auth0, while performing token verification and user data protection within the API routes.</p>
<pre><code class="language-typescript">// app/api/user/route.ts
import { verifyToken } from '@/lib/auth';

export async function GET(req: Request) {
  const token = req.headers.get('Authorization')?.replace('Bearer ', '');
  const user = await verifyToken(token);
  if (!user) return new Response('Unauthorized', { status: 401 });
  return new Response(JSON.stringify({ user }), { status: 200 });
}
</code></pre>
<p>📂 ③ Integration with external APIs (indirect proxy)</p>
<p>API Routes are often used as a proxy to integrate with external APIs (such as OpenAI, Stripe, and Google APIs).</p>
<pre><code class="language-typescript">// app/api/openai/route.ts
export async function POST(req: Request) {
  const { prompt } = await req.json();
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ model: 'gpt-4', messages: [{ role: 'user', content: prompt }] }),
  });

  const data = await response.json();
  return new Response(JSON.stringify({ result: data }), { status: 200 });
}
</code></pre>
<p>✅ Benefits</p>
<p>You can safely call the API without exposing the API key to the front end</p>
<p>Front-end code becomes simpler</p>
<p>💾 ④ Integration with Databases (Prisma / Supabase / Firestore)</p>
<p>It is common to perform database operations within Next.js API routes using ORMs (e.g., Prisma) or client SDKs (e.g., Supabase, Firebase).</p>
<pre><code class="language-typescript">// app/api/todos/route.ts
import { prisma } from '@/lib/prisma';

export async function GET() {
  const todos = await prisma.todo.findMany();
  return Response.json(todos);
}
</code></pre>
<p>✅ Benefits</p>
<p>Optimizes data retrieval processes in an SSR environment</p>
<p>Eliminates the need for client-side database knowledge  </p>
<p>4. Precautions and Best Practices for Using API Routes</p>
<p>While API Routes are convenient and flexible, improper design or operation can lead to spaghetti code and create security risks. In this chapter, we will introduce key points to keep in mind and best practices for using API Routes in real-world scenarios.  </p>
<p>🧱 Improve Readability with a Thoughtful Directory Structure</p>
<p>As the number of API routes increases, your files can become cluttered. By creating a subdirectory for each endpoint, you can achieve a scalable structure.  </p>
<pre><code class="language-plaintext">/app
 └── api
     ├── contact
     │    └── route.ts
     ├── auth
     │    └── login/route.ts
     │    └── logout/route.ts
     └── todos
          ├── route.ts
          └── [id]/route.ts
</code></pre>
<p>✅ Key point: Grouping by functional units or resources helps minimize confusion even in team-based development  </p>
<p>🔐 Standardize authentication and authorization mechanisms as much as possible</p>
<p>If many API routes require user authentication, it’s helpful to centralize authorization checks in <code>middleware.ts</code> or handle them in <code>lib/auth.ts</code>.</p>
<pre><code class="language-typescript">// lib/auth.ts
export async function getUserFromRequest(req: Request) {
  const token = extractToken(req);
  return await verifyToken(token);
}
</code></pre>
<p>✅ Key point: Hard-coding authentication logic for each API can easily lead to bugs.  </p>
<p>🚧 Handle errors carefully</p>
<p>To ensure that the client displays the correct information when an API call fails, proper error handling and clear HTTP status codes are essential.</p>
<pre><code class="language-typescript">try {
  const data = await fetchSomething();
  return Response.json(data);
} catch (error) {
  console.error(error);
  return new Response('Internal Server Error', { status: 500 });
}
</code></pre>
<p>✅ Key point: Receiving a specific error message rather than a “500 error” on the client side improves the user experience  </p>
<p>🚨 Division of Responsibilities with Client Components</p>
<p>Using <code>fetch(‘/api/~’)</code> directly in a Client Component tends to complicate state management and error handling.</p>
<p>Retrieve lightweight data using <code>useSWR</code> or React Query</p>
<p>Separate responsibilities for heavy processing into Server Components or API Routes</p>
<p>✅ Key Point: Clearly define where data is stored and where it is processed</p>
<p>📉 Don’t forget security measures like rate limiting and CSRF protection</p>
<p>The following measures are especially important for publicly exposed APIs (e.g., forms):</p>
<p>Rate Limit: Protection against bots and DDoS attacks</p>
<p>CSRF Token: Prevention of unintended requests</p>
<p>CORS Control: Allow requests only from authorized domains</p>
<p>✅ Key Point: Since Next.js alone cannot fully secure all areas, consider implementing a WAF or Cloudflare</p>
<p>✅ Conclusion | The key to API Routes is “simple design” Next.js API Routes are a very powerful feature for developing small to medium-sized applications. They are particularly well-suited for Server Components in App Router configurations and are ideal when you just need a “quick API.”</p>
<p>However, as the scale expands, considerations such as separation of concerns, security measures, and performance optimization become necessary.</p>
<p>In your own development, make sure to understand the “appropriate use cases” and “precautions” so you can use API Routes effectively.</p>
]]></content:encoded></item><item><title><![CDATA[App Router ~Parallel Routes~]]></title><description><![CDATA[What is Parallel Routes?
With Parallel Routes, you can render multiple pages simultaneously or conditionally within the same layout. Taking the dashboard as an example, you can render the team page an]]></description><link>https://kkr-netxjs-blog.hashnode.dev/app-router-parallel-routes</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/app-router-parallel-routes</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Sat, 04 Apr 2026 00:51:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/5d653e69-c3b9-46e5-b435-234a02f5b1f7.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>What is Parallel Routes?</p>
<p>With Parallel Routes, you can render multiple pages simultaneously or conditionally within the same layout. Taking the dashboard as an example, you can render the team page and the analytics page in parallel as shown below</p>
<img src="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/18e1b67a-a636-4d0b-a732-48828dcbe6e1.png" alt="" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[Routing  ~Private Folders~]]></title><description><![CDATA[In Next.js's App Router, a private folder is a feature that excludes a folder and its subfiles from URL routing by prefixing the folder name with an underscore (_) (e.g., _components). It is primarily]]></description><link>https://kkr-netxjs-blog.hashnode.dev/routing-private-folders</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/routing-private-folders</guid><category><![CDATA[Next.js]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Tue, 31 Mar 2026 23:02:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/996a6043-e4aa-4229-99e6-431da78be343.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Next.js's App Router, a <code>private folder</code> is a feature that excludes a folder and its subfiles from URL routing by prefixing the folder name with an underscore (_) (e.g., _components). It is primarily used when creating and organizing files such as components, styles, and shared logic, allowing you to place them without affecting the URL structure.</p>
<p><strong>Features and Main Uses</strong></p>
<p>Routing Exclusion: Even if placed under the <code>app</code> directory, the <code>page.js</code> file within it will not be recognized as a URL.</p>
<p>File Organization: You can organize and manage page-specific components, CSS, and utility functions by keeping them in a physically close location (within a folder).</p>
<p>Naming Conventions: Start with an underscore, such as <code>_folderName</code>.</p>
<p><strong>Examples of Use</strong></p>
<pre><code class="language-text">app/
├── (auth)/
├── dashboard/
│   ├── _components/  &lt;-- Private folder (not influence URL)
│   │   └── Chart.tsx
│   └── page.tsx      &lt;-- access dashboard page by /dashboard
└── page.tsx
</code></pre>
]]></content:encoded></item><item><title><![CDATA[App Route ~Catch-all Segments~]]></title><description><![CDATA[Dynamic Segments can be extended to catch-all subsequent segments by adding an ellipsis inside the brackets [...segmentName].
For example, pages/shop/[...slug].js will match /shop/clothes, but also /s]]></description><link>https://kkr-netxjs-blog.hashnode.dev/app-route-catch-all-segments</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/app-route-catch-all-segments</guid><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Sun, 29 Mar 2026 07:08:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/ce3c546f-5d19-485c-9dbb-947c086fbb18.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Dynamic Segments can be extended to catch-all subsequent segments by adding an ellipsis inside the brackets [...segmentName].</p>
<p>For example, <code>pages/shop/[...slug].js</code> will match <code>/shop/clothes</code>, but also <code>/shop/clothes/tops</code>, <code>/shop/clothes/tops/t-shirts</code>, and so on.</p>
<p>For example:</p>
<p><code>pages/shop/[...slug].js</code> <code>/shop/a</code>	<code>{ slug: ['a'] }</code></p>
<p><code>pages/shop/[...slug].js</code> <code>/shop/a/b</code> <code>{ slug: ['a', 'b'] }</code></p>
<p><code>pages/shop/[...slug].js</code> <code>/shop/a/b/c</code> <code>{ slug: ['a', 'b', 'c'] }</code></p>
<p>Catch-all segments ([...slug]) are extremely useful when URL hierarchies are deep and their exact depth is unknown. They are primarily used in the following three scenarios:</p>
<ol>
<li><p>Hierarchical structures for documentation or blogs
These are ideal for handling deep hierarchies—such as “category / subcategory / article title”—in a single template, as seen on documentation sites.
Example: app/docs/[...slug]/page.tsx</p>
</li>
<li><p>E-commerce Site Filtering
Used for structures where product categories, brands, sizes, etc., are concatenated as URL segments.
Example: /shop/clothes/tops/t-shirts
Advantage: Since each segment (clothes, tops...) can be retrieved as an array, it’s easy to reuse them directly as database query conditions.</p>
</li>
<li><p>Building CMSs and File Browsers
This is well-suited for systems where users can freely create folders (hierarchies), such as tools like Notion or file management systems like Google Drive.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[NextJs App Router ~Route Groups~]]></title><description><![CDATA[Route Groups in Next.js 16 allow you to organize folders within your app and apply layouts to specific routes without affecting the URL structure. By naming folders in the format (folder-name), they f]]></description><link>https://kkr-netxjs-blog.hashnode.dev/nextjs-app-router-route-groups</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/nextjs-app-router-route-groups</guid><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Fri, 27 Mar 2026 08:34:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/d7075ec6-0e55-415e-a6d0-640380b8442f.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Route Groups in Next.js 16 allow you to organize folders within your app and apply layouts to specific routes without affecting the URL structure. By naming folders in the format (folder-name), they function as organizational groups, enabling you to logically separate the route hierarchy.</p>
<p><strong>Key Features and Use Cases</strong></p>
<p>・Organization and Grouping: Organize directories by function, such as pre-login (auth) and post-login (dashboard).</p>
<p>・Selective Layout Application: Apply a common layout (layout.tsx) only within specific groups.</p>
<p>・No Impact on URLs: Grouped folder names are not reflected in the URL.</p>
<p>・Multiple Root Layouts: You can separate root layouts (including the <code>&lt;html&gt;</code> tag) for each root group within different app directories.</p>
<p><strong>Implementation Example</strong></p>
<p>By organizing the folder structure as shown below, you can flexibly manage the layout—for example, by using different layouts for the /about page depending on whether the user is authenticated.</p>
<pre><code class="language-text">app/
├── (auth)/
│   ├── login/
│   │   └── page.tsx
│   └── layout.tsx  // Login Layout
└── (dashboard)/
    ├── dashboard/
    │   └── page.tsx
    └── layout.tsx  // Dashboard Layout
</code></pre>
]]></content:encoded></item><item><title><![CDATA[NextJs App Router ~Dynamic Routes~]]></title><description><![CDATA[Dynamic Routes
Dynamic Routes are defined using square brackets []. For example, if you create a file named app/products/[id]/page.tsx, it will generate pages that match URLs such as /products/1 and /]]></description><link>https://kkr-netxjs-blog.hashnode.dev/nextjs-app-router-dynamic-routes</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/nextjs-app-router-dynamic-routes</guid><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Wed, 25 Mar 2026 12:16:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/9a6eeb1e-3bc4-4bc6-beba-b5e43ae68200.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1>Dynamic Routes</h1>
<p>Dynamic Routes are defined using square brackets []. For example, if you create a file named app/products/[id]/page.tsx, it will generate pages that match URLs such as /products/1 and /products/2.</p>
<p>app/<br />└── products/<br />　　　└── [id]/<br />　　　　　　└── page.tsx</p>
<pre><code class="language-app/products/[id]/page.tsx">export default function ProductPage({ params }: { params: { category: string, id: string } }) {
  return (
    &lt;&gt;
      &lt;h1&gt;Category: {params.category}&lt;/h1&gt;
      &lt;h2&gt;Product ID: {params.id}&lt;/h2&gt;
    &lt;/&gt;
  )
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[App router]]></title><description><![CDATA[NextJS's App Router is a modern framework built on React Server Components that centrally manages file-based routing, layouts, and data fetching within the app/ directory. It is faster than the tradit]]></description><link>https://kkr-netxjs-blog.hashnode.dev/app-router</link><guid isPermaLink="true">https://kkr-netxjs-blog.hashnode.dev/app-router</guid><category><![CDATA[Next.js]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[OGASAWARA KAKERU]]></dc:creator><pubDate>Sat, 21 Mar 2026 10:50:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/69bd1a84b238fd45a3902110/0c472075-8a3d-4b0f-a9d9-b709d06dc77c.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>NextJS's App Router is a modern framework built on React Server Components that centrally manages file-based routing, layouts, and data fetching within the <code>app/</code> directory. It is faster than the traditional Pages Router, makes server-side rendering the default, and enables more efficient SPA/MPA development.</p>
<p><strong>Key Features and Benefits of App Router</strong></p>
<p>・Advanced routing: The folder structure under the <code>app/</code> directory corresponds to URL paths. Define screens in <code>page.tsx</code> and common layouts in <code>layout.tsx</code>.</p>
<p>・Nested layouts: Layouts can be nested by folder, enabling efficient reuse of common UI elements.</p>
<p>・Improved data fetching: Data can be fetched directly within components using async/await. The fetch API has been extended to support powerful caching and revalidation.</p>
<p>・Simplified UI management: Simply placing loading.tsx (loading UI) and error.tsx (error handling) applies Suspense and Error Boundaries.</p>
<p><strong>Server Components vs Client Components</strong></p>
<p>・Server Components (.tsx): Default. Runs on the backend. Can access databases and APIs directly.</p>
<p>・Client Components (“use client”;): Used when interactivity (useState, useEffect, event listeners) is required</p>
]]></content:encoded></item></channel></rss>