How to add body class before rendering the page in Magento 2?

Magento 2 add body class with pages like cms, category, product and checkout page.

You can set cutom body class for the page in Magento 2 using plugin by Magento\Framework\View\Result\Page class.

If you want to add your own class for the page in <body> tag of the page, You can use the below code snippet to add class. Check the Path to define plugin: Jesadiya\BodyClass\etc\frontend\di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\View\Result\Page">
        <plugin name="add_body_class" type="Jesadiya\BodyClass\Plugin\Result\Page"/>
    </type>
</config>

Plugin class,
Path: Jesadiya\BodyClass\Plugin\Result\Page.php

<?php declare(strict_types=1);

namespace Jesadiya\BodyClass\Plugin\Result;

use Magento\Framework\App\ResponseInterface;
use Magento\Framework\View\Result\Page as ResultPage;

class Page
{
    /**
     * Add Body Class
     *
     * @param ResultPage $subject
     * @param ResponseInterface $response
     *
     * @return array
     */
    public function beforeRenderResult(
        ResultPage $subject,
        ResponseInterface $response
    ) : array {
        if ($subject->getConfig()->getPageLayout() == '1column'
        ) {
            $subject->getConfig()->addBodyClass('cms-static-page');
        }
        if ($subject->getConfig()->getPageLayout() == 'category-full-width') {
            $subject->getConfig()->addBodyClass('category-page');
        }

        return [$response];
    }
}

You can add body class based on the configuration layout from the admin panel, If you have set the layout type from the admin panel, you got the Page layout type from the $subject->getConfig()->getPageLayout().

You can set predefined layout type from the admin panel for the CMS page, Product page or Category page.

Output:
When you check the 1column page body class, new class will be appended to body tag.

You can set custom body class for any page with the Plugin with before Rende Result method.