This is a companion post to Astro + Storyblok: SSR preview for instant visual editing. Please read it first if you haven't already!
Below you'll find some extra tips and tricks I've discovered while developing my Astro + Storyblok site.
Remove drafts from the production site
To avoid loading draft content in production, I created a wrapper function for the Storyblok API:
// src/storyblok/utils.ts
import * as sb from '@storyblok/astro';
export const storyblokApi = (slug: string, params?: sb.ISbStoryParams) => {
const api = sb.useStoryblokApi();
return api.get(slug, {
version:
import.meta.env.PUBLIC_ENV === 'production' ? 'published' : 'draft',
...params,
});
};
You can then use this wrapper wherever you would've used the Storyblok API, e.g.:
// src/pages/[slug].astro
import { storyblokApi } from '../storyblok/utils';
export async function getStaticPaths() {
const { data } = await storyblokApi('cdn/links');
let links = data.links;
links = Object.values(links);
return links
.filter((link: any) => !['index', 'site-config'].includes(link.slug))
.map((link: any) => {
return {
params: { slug: link.slug },
};
});
}
// ...
Prevent search engine indexing of the preview site
You probably don't want your preview site containing drafts and unfinished content to be indexed by search engines. To prevent that, use the astro-robots-txt
integration:
npx astro add astro-robots-txt
// astro.config.{mjs,ts}
import robotsTxt from 'astro-robots-txt';
// ...
export default defineConfig({
// ...
integrations: [
robotsTxt({
policy: [
{
userAgent: '*',
disallow: process.env.PUBLIC_ENV !== 'production' ? '/' : '',
},
],
}),
// ...
],
// ...
});
Disable astro-imagetools
image processing in SSR
I found that my SSR pages loaded very slowly because I was using astro-imagetools
to process images. Since optimized images aren't necessary during editing anyways, I created a wrapper component to bypass image processing in the preview environment:
---
import type { Picture } from 'astro-imagetools/components';
export type Props = Parameters<typeof Picture>[0];
let {
breakpoints = [500, 900, 1800], // fallback breakpoints
class: pictureClass = '',
...props
} = Astro.props;
let Component;
if (import.meta.env.PUBLIC_ENV === 'preview') {
Component = 'img';
props = {
class: pictureClass,
...props,
};
} else {
Component = (await import('astro-imagetools/components')).Picture;
props = {
breakpoints,
attributes: {
picture: {
class: pictureClass,
},
},
...props,
};
}
---
<Component {...props} />
Top comments (0)