Replies: 2 comments 2 replies
-
WorkaroundWrap the
import 'server-only';
import { unstable_noStore as noStore } from 'next/cache';
import postgres, { Sql } from 'postgres';
declare module globalThis {
let postgresSqlClient: Sql;
}
// Connect only once to the database
// https://github.com/vercel/next.js/issues/7811#issuecomment-715259370
function connectOneTimeToDatabase() {
if (!('postgresSqlClient' in globalThis)) {
globalThis.postgresSqlClient = postgres();
}
// Workaround to force Next.js Dynamic Rendering on every database query:
//
// Wrap sql`` tagged template function to call `noStore()` from
// next/cache before each database query. `noStore()` is a
// Next.js Dynamic Function, which causes the page to use
// Dynamic Rendering
//
// https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic-rendering
//
// Ideally there would something built into Next.js for this,
// which has been requested here:
//
// https://github.com/vercel/next.js/discussions/50695
return ((
...sqlParameters: Parameters<typeof globalThis.postgresSqlClient>
) => {
noStore();
return globalThis.postgresSqlClient(...sqlParameters);
}) as typeof globalThis.postgresSqlClient;
}
export const sql = connectOneTimeToDatabase(); Then any usage of
import { sql } from '../database/connect';
export default async function Page() {
// ✅ Any usage of sql`...` will trigger Dynamic Rendering, just like headers() would
const animals = await sql`SELECT * FROM animals`;
return (
<div>
<ul>
{animals.map((animal) => (
<li key={animal.id}>{animal.name}</li>
)}
</ul>
</div>
);
} cc @sebmarkbage what are your thoughts on a built-in API for this in Next.js? eg. |
Beta Was this translation helpful? Give feedback.
-
The |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Goals
force-dynamic
orrevalidate = 0
Background
Currently a Server Component such as
Is flagged as a Static Page since is not fitting the Dynamic Rendering requirements of Next.js. This would be different if the database query would be performed from an API route or if a Dynamic Function is called.
Proposal
I understand it is possible to configure this segments as dynamic either using
dynamic=force-dynamic
orrevalidate=0
. But I think it would be better if Next.js recognises this components as Dynamic Rendering by default. Maybe one possible option is recognising if the Database Query is using react/cache.Something that can also be nice to have is using a syntax similar to
server only
.so basically if use something like import
dynamic only
at the top of a file, this would enforce Dynamic Rendering when is imported on a server component.another option would be something like
import 'next/force-dynamic'
Beta Was this translation helpful? Give feedback.
All reactions