Serverless functions

Oh boy, serverless functions … it sounds like a technical challenge. But is it? No, not really. I always thought it would be hard, create some code not hosted anywhere, because it’s serverless. How would that work?

After some digging and asking around the concept is rather simple, only the naming “serverless function” is a bit silly and plainly put just fools you. At least, it fooled me.

After reading the concept written on the Vercel website, a serverless function is just a piece code just responsible for doing one thing. Oh good, we’re making things SOLID, cool! But how? Also this is not that hard, certainly not with NextJS and hosting our app at Vercel. If we would place our piece code (just doing one thing) in our NextJS app in a file within the /pages/api folder we already have a so called serverless function.

In our case, where we are going headless upon WordPress, we can create a serverless function to fetch content of a page or blog post. The benefit of this, is that would have only one function, in one file, responsible of fetching content data instead of fetching content all over the place.

So, let’s move the code of fetching content into a serverless function. To do this, we create a file called /pages/api/page-or-post/[[…slug]].ts and move the fetches from in here.

import type {NextApiRequest, NextApiResponse} from 'next'

const handler = async (
    request: NextApiRequest,
    response: NextApiResponse
) => {
    const slug = request.query.slug;
    
    // try to get page
    const page = await fetch(`https://<your.domain.com>/wp-json/wp/v2/pages?status=publish&slug=${slug}`)
        .then(data => data.json());
    if (page && page.length) {
        response.status(200).json(page[0]);
        return;
    }

    // if failed, try to get post
    const post = await fetch(`https://<your.domain.com>/wp-json/wp/v2/posts?status=publish&slug=${slug}`)
        .then(data => data.json());
    if (post && post.length) {
        response.status(200).json(post[0]);
        return;
    }

    // else 404
    response.status(404).json({});
}

export default handler;

Now we don’t need to fetch content from WordPress in our page. Instead we call the serverless function.

export const getServerSideProps = async (context) => {
    const slug = context.query.slug ?
        context.query.slug.join('/') :
        '';

    const data = await fetch(`http://localhost:3000/api/page-or-post/${slug}`)
        .then(data => data.json());

    return {
        props: {
            slug: slug
            data: data
        }
    };
}

const Page = ({slug, data}) => {
    return (
        <>
            Hello World on /{slug}
            <h1>{data.title.rendered}</h1>
            <div dangerouslySetInnerHTML={{__html: data.content.rendered}}/>
        </>
    )
}

export default Page;

Leave a comment

Your email address will not be published. Required fields are marked *