CodShot
TypeScript Public

Next.js Cached Data with use cache

Cache a server data function and attach a reusable invalidation tag.

#nextjs #caching #server-components #typescript
TypeScript
// app/lib/posts.ts

import {
  cacheLife,
  cacheTag,
} from 'next/cache';

export async function getPublishedPosts() {
  'use cache';

  cacheLife('hours');
  cacheTag('posts');

  return db.post.findMany({
    where: {
      published: true,
    },
    orderBy: {
      createdAt: 'desc',
    },
    take: 20,
  });
}

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support