Getting Prismic Previews to work with a static Nuxt site hosted on Netlify
Getting Prismic Previews to work with a statically generated Nuxt site
# install dependencies
npm run install
# serve with hot reload at localhost:3000
npm run dev
# build for production and launch server
npm run build
npm run start
# generate static project
npm run generate
For detailed explanation on how things work, check out Nuxt.js docs.
Spin up a new Nuxt project with create-nuxt-app
Follow Prismic's Using Prismic with Nuxt.js guide
Make sure you have a /preview
route by following the instructions in the "Setting up your preview route" section of Prismic's Using Prismic with Nuxt.js guide
Add a file to the middleware
folder called preview.js
Declare the middleware to the router
object in your nuxt.config.js
// nuxt.config.js
router: {
middleware: 'preview',
},
Paste the following in your preview middleware (adopted from prismic-nuxt
)
// middleware/preview.js
import Prismic from 'prismic-javascript';
import PrismicConfig from '~/prismic.config.js';
import LinkResolver from '~/plugins/link-resolver.js';
export default async function(context) {
const { route, query, redirect, res } = context;
const api = Prismic.getApi(PrismicConfig.apiEndpoint);
if (route.path === '/preview') {
const { token } = query;
if (token) {
const url = await api.previewSession(token, LinkResolver, '/');
const cookie = [
`${Prismic.previewCookie}=${token}`,
`max-age=${30 * 60 * 1000}`,
'path=/',
].join('; ');
if (process.server) {
// Server-side
res.setHeader('Set-Cookie', [cookie]);
} else {
// Client-side
document.cookie = cookie;
}
redirect(302, url);
} else {
redirect(302, '/');
}
}
}
Hack to fetch preview content with a static site
Since Nuxt won't automatically run the asyncData
function again to fetch the data you want to preview, we have to use the created
lifecycle hook to force the page to get preview content from Prismic instead of the actual published content.
// pages/mypage.vue
<script>
import Prismic from 'prismic-javascript';
import PrismicConfig from '~/prismic.config.js';
async function getPage(options = {}) {
const api = await Prismic.getApi(PrismicConfig.apiEndpoint, options);
return api.getByUID('page', 'my-page');
}
export default {
async asyncData({ app, context, error, req }) {
try {
const result = await getPage({ req });
return {
document: result.data,
documentId: result.id,
};
} catch (e) {
error({ statusCode: 404, message: 'Page not found' });
}
},
created() {
this.refetchPageforPreview();
},
methods: {
async refetchPageForPreview() {
try {
const result = await getPage();
this.document = result.data;
} catch (e) {
error({ statusCode: 404, message: 'Page not found' });
}
},
},
};
</script>
In your Prismic repo go to Settings
-> Previews
-> Create a Preview
Once deployed to Netlify, fill in the details with /preview
in the Link Resolver
field