{"id":13469598,"url":"https://github.com/ricokahler/next-plugin-preval","last_synced_at":"2025-05-15T09:07:30.798Z","repository":{"id":39238325,"uuid":"332989833","full_name":"ricokahler/next-plugin-preval","owner":"ricokahler","description":"Pre-evaluate async functions during builds and import them like JSON","archived":false,"fork":false,"pushed_at":"2025-05-02T21:57:45.000Z","size":2115,"stargazers_count":255,"open_issues_count":15,"forks_count":13,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-05-02T22:33:10.090Z","etag":null,"topics":["jamstack","nextjs","preevaluation","ssg"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ricokahler.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-01-26T06:13:25.000Z","updated_at":"2025-03-28T18:54:50.000Z","dependencies_parsed_at":"2023-02-12T00:16:02.057Z","dependency_job_id":"97a54a93-adbc-424f-abb3-911a561e4522","html_url":"https://github.com/ricokahler/next-plugin-preval","commit_stats":{"total_commits":130,"total_committers":10,"mean_commits":13.0,"dds":0.6076923076923078,"last_synced_commit":"701368a3ca33a7ffafa54f413726f1c4abc3b2e7"},"previous_names":[],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ricokahler%2Fnext-plugin-preval","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ricokahler%2Fnext-plugin-preval/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ricokahler%2Fnext-plugin-preval/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ricokahler%2Fnext-plugin-preval/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ricokahler","download_url":"https://codeload.github.com/ricokahler/next-plugin-preval/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254310515,"owners_count":22049469,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["jamstack","nextjs","preevaluation","ssg"],"created_at":"2024-07-31T15:01:46.397Z","updated_at":"2025-05-15T09:07:25.770Z","avatar_url":"https://github.com/ricokahler.png","language":"TypeScript","funding_links":[],"categories":["Nextjs Plugins","TypeScript"],"sub_categories":[],"readme":"# next-plugin-preval · [![codecov](https://codecov.io/gh/ricokahler/next-plugin-preval/branch/main/graph/badge.svg?token=ZMYB4EW4SH)](https://codecov.io/gh/ricokahler/next-plugin-preval) [![github status checks](https://badgen.net/github/checks/ricokahler/next-plugin-preval/main)](https://github.com/ricokahler/next-plugin-preval/actions) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)\n\n\u003e Pre-evaluate async functions (for data fetches) at build time and import them like JSON\n\n```js\n// data.preval.js (or data.preval.ts)\n\n// step 1: create a data.preval.js (or data.preval.ts) file\nimport preval from 'next-plugin-preval';\n\n// step 2: write an async function that fetches your data\nasync function getData() {\n  const { title, body } = await /* your data fetching function */;\n  return { title, body };\n}\n\n// step 3: export default and wrap with `preval()`\nexport default preval(getData());\n```\n\n```js\n// Component.js (or Component.ts)\n\n// step 4: import the preval\nimport data from './data.preval';\n\n// step 5: use the data. (it's there synchronously from the build step!)\nconst { title, body } = data;\n\nfunction Component() {\n  return (\n    \u003c\u003e\n      \u003ch1\u003e{title}\u003c/h1\u003e\n      \u003cp\u003e{body}\u003c/p\u003e\n    \u003c/\u003e\n  );\n}\n\nexport default Component;\n```\n\n## Why?\n\nThe primary mechanism Next.js provides for static data is `getStaticProps` — which is a great feature and is the right tool for many use cases. However, there are other use cases for static data that are not covered by `getStaticProps`.\n\n- **Site-wide data**: if you have static data that's required across many different pages, `getStaticProps` is a somewhat awkward mechanism because for each new page, you'll have to re-fetch that same static data. For example, if you use `getStaticProps` to fetch content for your header, that data will be re-fetched on every page change.\n- **Static data for API routes**: It can be useful to pre-evaluate data fetches in API routes to speed up response times and offload work from your database. `getStaticProps` does not work for API routes while `next-plugin-preval` does.\n- **De-duped and code split data**: Since `next-plugin-preval` behaves like importing JSON, you can leverage the optimizations bundlers have for importing standard static assets. This includes standard code-splitting and de-duping.\n- **Zero runtime**: Preval files don't get sent to the browser, only their outputted JSON.\n\nSee the [recipes](#recipes) for concrete examples.\n\n## Installation\n\n### Install\n\n```\nyarn add next-plugin-preval\n```\n\nor\n\n```\nnpm i next-plugin-preval\n```\n\n### Add to next.config.js\n\n```js\n// next.config.js\nconst createNextPluginPreval = require('next-plugin-preval/config');\nconst withNextPluginPreval = createNextPluginPreval();\n\nmodule.exports = withNextPluginPreval(/* optionally add a next.js config */);\n```\n\n## Usage\n\nCreate a file with the extension `.preval.ts` or `.preval.js` then export a promise wrapped in `preval()`.\n\n```js\n// my-data.preval.js\nimport preval from 'next-plugin-preval';\n\nasync function getData() {\n  return { hello: 'world'; }\n}\n\nexport default preval(getData());\n```\n\nThen import that file anywhere. The result of the promise is returned.\n\n```js\n// component.js (or any file)\nimport myData from './my-data.preval'; // 👈 this is effectively like importing JSON\n\nfunction Component() {\n  return (\n    \u003cdiv\u003e\n      \u003cpre\u003e{JSON.stringify(myData, null, 2)}\u003c/pre\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default Component;\n```\n\nWhen you import a `.preval` file, it's like you're importing JSON. `next-plugin-preval` will run your function during the build and inline a JSON blob as a module.\n\n## ⚠️ Important notes\n\nThis works via a webpack loader that takes your code, compiles it, and runs it inside of Node.js.\n\n- Since this is an optimization at the bundler level, it will not update with Next.js [preview mode](https://nextjs.org/docs/advanced-features/preview-mode), during dynamic SSR, or even [ISR](https://nextjs.org/docs/basic-features/data-fetching#incremental-static-regeneration). Once this data is generated during the initial build, it can't change. It's like importing JSON. See [this pattern](#supporting-preview-mode) for a work around.\n- Because this plugin runs code directly in Node.js, code is not executed in the typical Next.js server context. This means certain injections Next.js does at the bundler level will not be available. We try our best to mock this context via [`require('next')`](https://github.com/ricokahler/next-plugin-preval/issues/12). For most data queries this should be sufficient, however please [open an issue](https://github.com/ricokahler/next-plugin-preval/issues/new) if something seems off.\n\n## Recipes\n\n### Site-wide data: Shared header\n\n```js\n// header-data.preval.js\nimport preval from 'next-plugin-preval';\n\nasync function getHeaderData() {\n  const headerData = await /* your data fetching function */;\n\n  return headerData;\n}\n\nexport default preval(getHeaderData());\n```\n\n```js\n// header.js\nimport headerData from './header-data.preval';\nconst { title } = headerData;\n\nfunction Header() {\n  return \u003cheader\u003e{title}\u003c/header\u003e;\n}\n\nexport default Header;\n```\n\n### Static data for API routes: Pre-evaluated listings\n\n```js\n// products.preval.js\nimport preval from 'next-plugin-preval';\n\nasync function getProducts() {\n  const products = await /* your data fetching function */;\n\n  // create a hash-map for O(1) lookups\n  return products.reduce((productsById, product) =\u003e {\n    productsById[product.id] = product;\n    return productsById;\n  }, {});\n}\n\nexport default preval(getProducts());\n```\n\n```js\n// /pages/api/products/[id].js\nimport productsById from '../products.preval.js';\n\nconst handler = (req, res) =\u003e {\n  const { id } = req.params;\n\n  const product = productsById[id];\n\n  if (!product) {\n    res.status(404).end();\n    return;\n  }\n\n  res.json(product);\n};\n\nexport default handler;\n```\n\n### Code-split static data: Loading non-critical data\n\n```js\n// states.preval.js\nimport preval from 'next-plugin-preval';\n\nasync function getAvailableStates() {\n  const states = await /* your data fetching function */;\n  return states;\n}\n\nexport default preval(getAvailableStates());\n```\n\n```js\n// state-picker.js\nimport { useState, useEffect } from 'react';\n\nfunction StatePicker({ value, onChange }) {\n  const [states, setStates] = useState([]);\n\n  useEffect(() =\u003e {\n    // ES6 dynamic import\n    import('./states.preval').then((response) =\u003e setStates(response.default));\n  }, []);\n\n  if (!states.length) {\n    return \u003cdiv\u003eLoading…\u003c/div\u003e;\n  }\n\n  return (\n    \u003cselect value={value} onChange={onChange}\u003e\n      {states.map(({ label, value }) =\u003e (\n        \u003coption key={value} value={value}\u003e\n          {label}\n        \u003c/option\u003e\n      ))}\n    \u003c/select\u003e\n  );\n}\n```\n\n### Supporting preview mode\n\nAs stated in the [notes](#%EF%B8%8F-important-notes), the result of next-plugin-preval won't change after it leaves the build. However, you can still make preview mode work if you extract your data fetching function and conditionally call it based on preview mode (via [`context.preview`](https://nextjs.org/docs/advanced-features/preview-mode#step-2-update-getstaticprops). If preview mode is not active, you can default to the preval file.\n\n```js\n// get-data.js\n\n// 1. extract a data fetching function\nasync function getData() {\n  const data = await /* your data fetching function */;\n  return data\n}\n```\n\n```js\n// data.preval.js\nimport preval from 'next-plugin-preval';\nimport getData from './getData';\n\n// 2. use that data fetching function in the preval\nexport default preval(getData());\n```\n\n```js\n// /pages/some-page.js\nimport data from './data.preval';\nimport getData from './get-data';\n\nexport async function getStaticProps(context) {\n  // 3. conditionally call the data fetching function defaulting to the prevalled version\n  const data = context.preview ? await getData() : data;\n  \n  return { props: { data } };\n}\n```\n\n## Related Projects\n\n- [`next-data-hooks`](https://github.com/ricokahler/next-data-hooks) — creates a pattern to use `getStaticProps` as React hooks. Great for the site-wide data case when preview mode or ISR is needed.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fricokahler%2Fnext-plugin-preval","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fricokahler%2Fnext-plugin-preval","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fricokahler%2Fnext-plugin-preval/lists"}