All Projects → ricokahler → next-plugin-preval

ricokahler / next-plugin-preval

Licence: MIT License
Pre-evaluate async functions during builds and import them like JSON

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to next-plugin-preval

Api Platform
Create REST and GraphQL APIs, scaffold Jamstack webapps, stream changes in real-time.
Stars: ✭ 7,144 (+4005.75%)
Mutual labels:  nextjs, jamstack
Next Js Blog Boilerplate
🚀 Nextjs Blog Boilerplate is starter code for your blog based on Next framework. ⚡️ Made with Nextjs, TypeScript, ESLint, Prettier, PostCSS, Tailwind CSS.
Stars: ✭ 134 (-22.99%)
Mutual labels:  nextjs, jamstack
Jamstackthemes
A list of themes and starters for JAMstack sites.
Stars: ✭ 298 (+71.26%)
Mutual labels:  nextjs, jamstack
devdevdev
The next trendy apparel e-commerce store maybe?
Stars: ✭ 27 (-84.48%)
Mutual labels:  nextjs, ssg
vscode-azurestaticwebapps
Azure Static Web Apps extension for VS Code
Stars: ✭ 63 (-63.79%)
Mutual labels:  jamstack, ssg
Commercejs Nextjs Demo Store
Commerce demo store built for the Jamstack. Built with Commerce.js, Next.js, and can be one-click deployed to Netlify. Includes product catalog, categories, variants, cart, checkout, payments (Stripe) order confirmation, and printable receipts.
Stars: ✭ 737 (+323.56%)
Mutual labels:  nextjs, jamstack
Tinacms.org
Organization site for general info, documentation, blogs & contribution guidelines.
Stars: ✭ 94 (-45.98%)
Mutual labels:  nextjs, jamstack
Strapi Starter Next Corporate
Next.js starter for creating a corporate site with Strapi.
Stars: ✭ 145 (-16.67%)
Mutual labels:  nextjs, jamstack
corejam
A scaffolding for building progressive GraphQL powered jamstack applications.
Stars: ✭ 24 (-86.21%)
Mutual labels:  jamstack, ssg
Next.js
The React Framework
Stars: ✭ 78,384 (+44948.28%)
Mutual labels:  nextjs, ssg
greenwood
Greenwood is your workbench for the web, focused on supporting modern web standards and development to help you create your next project.
Stars: ✭ 48 (-72.41%)
Mutual labels:  jamstack, ssg
trailing-slash-guide
Understand and fix your static website trailing slash issues!
Stars: ✭ 255 (+46.55%)
Mutual labels:  jamstack, ssg
jamstack-preview-and-deployments
Preview and deploy NextJS applications from the wordpress admin.
Stars: ✭ 17 (-90.23%)
Mutual labels:  nextjs, jamstack
adeolaadeoti-v2
The second iteration of my portfolio
Stars: ✭ 67 (-61.49%)
Mutual labels:  nextjs
jeffjadulco.com
👽 Personal website running on Next.js
Stars: ✭ 54 (-68.97%)
Mutual labels:  nextjs
wodle
Static site generator using next and tachyons
Stars: ✭ 29 (-83.33%)
Mutual labels:  nextjs
saleor-storefront
A GraphQL-powered, NextJs-based, PWA storefront for Saleor. IMPORTANT: This project is [DEPRACETED] in favor of saleor/react-storefront soon to become our default demo and storefront starter pack.
Stars: ✭ 765 (+339.66%)
Mutual labels:  nextjs
onlysetups
OnlyFans, but for pictures of desk setups.
Stars: ✭ 82 (-52.87%)
Mutual labels:  nextjs
Kobra
Kobra is a visual programming language (like Scratch) for Machine Learning (currently under active development).
Stars: ✭ 223 (+28.16%)
Mutual labels:  nextjs
said-hayani-nextjs
Said Hayani personal blog built with NextJs
Stars: ✭ 17 (-90.23%)
Mutual labels:  nextjs

next-plugin-preval · codecov github status checks semantic-release

Pre-evaluate async functions (for data fetches) at build time and import them like JSON

// data.preval.js (or data.preval.ts)

// step 1: create a data.preval.js (or data.preval.ts) file
import preval from 'next-plugin-preval';

// step 2: write an async function that fetches your data
async function getData() {
  const { title, body } = await /* your data fetching function */;
  return { title, body };
}

// step 3: export default and wrap with `preval()`
export default preval(getData());
// Component.js (or Component.ts)

// step 4: import the preval
import data from './data.preval';

// step 5: use the data. (it's there synchronously from the build step!)
const { title, body } = data;

function Component() {
  return (
    <>
      <h1>{title}</h1>
      <p>{body}</p>
    </>
  );
}

export default Component;

Why?

The 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.

  • 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.
  • 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.
  • 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.
  • Zero runtime: Preval files don't get sent to the browser, only their outputted JSON.

See the recipes for concrete examples.

Installation

Install

yarn add next-plugin-preval

or

npm i next-plugin-preval

Add to next.config.js

// next.config.js
const createNextPluginPreval = require('next-plugin-preval/config');
const withNextPluginPreval = createNextPluginPreval();

module.exports = withNextPluginPreval(/* optionally add a next.js config */);

Usage

Create a file with the extension .preval.ts or .preval.js then export a promise wrapped in preval().

// my-data.preval.js
import preval from 'next-plugin-preval';

async function getData() {
  return { hello: 'world'; }
}

export default preval(getData());

Then import that file anywhere. The result of the promise is returned.

// component.js (or any file)
import myData from './my-data.preval'; // 👈 this is effectively like importing JSON

function Component() {
  return (
    <div>
      <pre>{JSON.stringify(myData, null, 2)}</pre>
    </div>
  );
}

export default Component;

When 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.

⚠️ Important notes

This works via a webpack loader that takes your code, compiles it, and runs it inside of Node.js.

  • Since this is an optimization at the bundler level, it will not update with Next.js preview mode, during dynamic SSR, or even ISR. Once this data is generated during the initial build, it can't change. It's like importing JSON. See this pattern for a work around.
  • 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'). For most data queries this should be sufficient, however please open an issue if something seems off.

Recipes

Site-wide data: Shared header

// header-data.preval.js
import preval from 'next-plugin-preval';

async function getHeaderData() {
  const headerData = await /* your data fetching function */;

  return headerData;
}

export default preval(getHeaderData());
// header.js
import headerData from './header-data.preval';
const { title } = headerData;

function Header() {
  return <header>{title}</header>;
}

export default Header;

Static data for API routes: Pre-evaluated listings

// products.preval.js
import preval from 'next-plugin-preval';

async function getProducts() {
  const products = await /* your data fetching function */;

  // create a hash-map for O(1) lookups
  return products.reduce((productsById, product) => {
    productsById[product.id] = product;
    return productsById;
  }, {});
}

export default preval(getProducts());
// /pages/api/products/[id].js
import productsById from '../products.preval.js';

const handler = (req, res) => {
  const { id } = req.params;

  const product = productsById[id];

  if (!product) {
    res.status(404).end();
    return;
  }

  res.json(product);
};

export default handler;

Code-split static data: Loading non-critical data

// states.preval.js
import preval from 'next-plugin-preval';

async function getAvailableStates() {
  const states = await /* your data fetching function */;
  return states;
}

export default preval(getAvailableStates());
// state-picker.js
import { useState, useEffect } from 'react';

function StatePicker({ value, onChange }) {
  const [states, setStates] = useState([]);

  useEffect(() => {
    // ES6 dynamic import
    import('./states.preval').then((response) => setStates(response.default));
  }, []);

  if (!states.length) {
    return <div>Loading…</div>;
  }

  return (
    <select value={value} onChange={onChange}>
      {states.map(({ label, value }) => (
        <option key={value} value={value}>
          {label}
        </option>
      ))}
    </select>
  );
}

Supporting preview mode

As stated in the 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. If preview mode is not active, you can default to the preval file.

// get-data.js

// 1. extract a data fetching function
async function getData() {
  const data = await /* your data fetching function */;
  return data
}
// data.preval.js
import preval from 'next-plugin-preval';
import getData from './getData';

// 2. use that data fetching function in the preval
export default preval(getData());
// /pages/some-page.js
import data from './data.preval';
import getData from './get-data';

export async function getStaticProps(context) {
  // 3. conditionally call the data fetching function defaulting to the prevalled version
  const data = context.preview ? await getData() : data;
  
  return { props: { data } };
}

Related Projects

  • 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.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].