Get started with Next.js

Overview

This covers integrating Plasmic into your existing Next.js codebase in three steps.

Want to generate a new codebase with Plasmic already integrated? Follow this quickstart instead!

Installation

npm install @plasmicapp/loader-nextjs
# or yarn add @plasmicapp/loader-nextjs

Initialization

Initialize Plasmic with the project ID and public API token. Define this in its own module to make it available globally.

./plasmic-init.ts
import { initPlasmicLoader } from "@plasmicapp/loader-nextjs";
export const PLASMIC = initPlasmicLoader({
projects: [
{
id: "PROJECTID", // ID of a project you are using
token: "APITOKEN" // API token for that project
}
],
// Fetches the latest revisions, whether or not they were unpublished!
// Disable for production to ensure you render only published changes.
preview: true,
})

To find your project’s public API token: open the project in Plasmic Studio, and click the Code toolbar button.

Render a single Plasmic page or component

We use Next.js’s getStaticProps() to fetch the design statically.

pages/mypage.tsx
import { initPlasmicLoader, PlasmicRootProvider, PlasmicComponent, ComponentRenderData } from '@plasmicapp/loader-nextjs';
import { PLASMIC } from '../plasmic-init';
// Statically fetch the data needed to render Plasmic pages or components.
export const getStaticProps = async () => {
// You can pass in multiple page paths or component names.
const plasmicData = await PLASMIC.fetchComponentData('PATH_OR_COMPONENT');
return {
props: {
plasmicData
// ...
}
};
};
// Render the page or component from Plasmic.
export default function MyPage(props: { plasmicData: ComponentRenderData }) {
return (
<PlasmicRootProvider loader={PLASMIC} prefetchedData={props.plasmicData}>
<PlasmicComponent component="PATH_OR_COMPONENT" />
</PlasmicRootProvider>
);
}

Auto load all Plasmic pages

To automatically render all Plasmic-defined pages at the routes specified in Plasmic, create a Next.js catch-all page.

Create either:

  • pages/[[...catchall]].tsx if you want the / route to render the corresponding Plasmic page (you must not have an existing pages/index.tsx), or
  • pages/[...catchall].tsx otherwise.

In all cases, the Plasmic page will only be there if there is no existing page already in pages/... for that route.

pages/[[...catchall]].tsx
import * as React from 'react';
import { PlasmicComponent, ComponentRenderData, PlasmicRootProvider, initPlasmicLoader } from '@plasmicapp/loader-nextjs';
import { GetStaticPaths, GetStaticProps } from 'next';
import Error from 'next/error';
import { PLASMIC } from '../plasmic-init';
/**
* Use fetchPages() to fetch list of pages that have been created in Plasmic
*/
export const getStaticPaths: GetStaticPaths = async () => {
const pages = await PLASMIC.fetchPages();
return {
paths: pages.map((page) => ({
params: { catchall: page.path.substring(1).split('/') }
})),
fallback: false
};
};
/**
* For each page, pre-fetch the data we need to render it
*/
export const getStaticProps: GetStaticProps = async (context) => {
const { catchall } = context.params ?? {};
// Convert the catchall param into a path string
const plasmicPath = typeof catchall === 'string' ? catchall : Array.isArray(catchall) ? `/${catchall.join('/')}` : '/';
const plasmicData = await PLASMIC.maybeFetchComponentData(plasmicPath);
if (plasmicData) {
// This is a path that Plasmic knows about; pass the data
// in as props
return {
props: { plasmicData }
};
} else {
// This is some non-Plasmic catch-all page
return {
props: {}
};
}
};
/**
* Actually render the page!
*/
export default function CatchallPage(props: { plasmicData?: ComponentRenderData }) {
const { plasmicData } = props;
if (!plasmicData || plasmicData.entryCompMetas.length === 0) {
return <Error statusCode={404} />;
}
return (
// Pass in the data fetched in getStaticProps as prefetchedData
<PlasmicRootProvider loader={PLASMIC} prefetchedData={plasmicData}>
{
// plasmicData.entryCompMetas[0].name contains the name
// of the component you fetched.
}
<PlasmicComponent component={plasmicData.entryCompMetas[0].name} />
</PlasmicRootProvider>
);
}

There’s much more to explore!

  • Bring your own React components into Plasmic.
  • Perform server-side rendering.
  • Render different variants.
  • Override the content or props.
  • Add dynamic behavior.
Continue learning in the docs.