justyna
justyna

Reputation: 21

ApostropheCMS - how to serve different page in middleware

I have ApostropheCMS v3 project. I want to add some middleware inside modules/@apostrophecms/page/index.js. I believe it sould look like this:

module.exports = {
  ...
  handlers(self, options) {
    return {
      "@apostrophecms/page:serve": {
        handleCustomLocales(req) {
          try {
            // code will go here
          } catch (_err) {}
        },

Let's say that the user opened "/en/contact" page. The contact page from EN locale was served by default.

I want to catch a few exceptions. If user opened "/en-cz/contact" ("/en-**/contact") page - I want to still serve contact page from EN locale. For now, it serves 404 page.

I don't want to change the url or redirect user to "/en/contact". How can I do it?

Upvotes: 0

Views: 90

Answers (1)

Tom Boutell
Tom Boutell

Reputation: 7572

First, just a warning: serving identical content for two different URLs without a canonical tag can affect your SEO. If you can't use a redirect (which I would recommend), consider outputting a canonical link tag in this situation.

OK, that being said:

To add true Express middleware, which is what you need here, you want to use Apostrophe's middleware feature in any module, like this:

module.exports = {
  ...
  middleware(self, options) {
    return {
      altLocales: {
        before: '@apostrophecms/i18n',
        middleware(req, res, next) {
          req.path = req.path.replace('/en-cz', '/en');
          req.url = req.url.replace('/en-cz', '/en');
          return next();
        }
      }
    };
  }
};

The before property schedules this middleware before the middleware installed by the @apostrophecms/i18n module, which ensures that req.locale is not decided before your middleware has a chance to run.

Of course you can use options here to make decisions about what to do based on configuration, and be more careful about ensuring /en-cz is only at the start of the path. This is a simple example demonstrating the technique.

Upvotes: 1

Related Questions