Tirraa / dashboard_rtm

dashboard_rtm
MIT License
5 stars 1 forks source link

[Perf][Bundle size] Segregate pages, rewrite URLs #85

Closed gustaveWPM closed 7 months ago

gustaveWPM commented 7 months ago

Well, well, well...

I thought pages with /[locale]/[...path] were a good idea.

But in practice, this is terrible. It makes the bundle size heavier than expected since it leads to unnecessary shared JS.

We should use /[locale]/pages/[...path], as we did with /[locale]/lp/[lp-slug]

Also, I'm very frustrated because of those ugly URL segments like lp or pages. So, I would love some URL rewriting to make them disappear.

Also, make sure that the generated sitemap will stay valid!

gustaveWPM commented 7 months ago

Well... It would involve two things:

  1. Rewrite the URLs
  2. Generate and inject all the redirections

The 1st one is achievable with middleware, like so:

// myRewrite.ts
import type { NextMiddleware, NextFetchEvent, NextRequest } from 'next/server';

import { NextResponse } from 'next/server';

const REWRITE_ME = '/rewrite-me/';

function getRewrittenPath(path: string) {
  if (path.endsWith(REWRITE_ME.slice(0, -1)) && path.length === REWRITE_ME.length - 1) {
    return '/';
  }
  return path.replace(REWRITE_ME, '/');
}

const doMyRewrite = (next: NextMiddleware) => {
  return async (request: NextRequest, _next: NextFetchEvent) => {
    console.log('Running middleware...');

    await next(request, _next); // * ... Calling the next chain element

    const nextUrl = request.nextUrl;
    const path = getRewrittenPath(nextUrl.pathname);
    nextUrl.pathname = path;

    const response = NextResponse.rewrite(nextUrl);
    console.log(response);
    return response;
  };
};

const myRewrite = (next: NextMiddleware) => doMyRewrite(next);

export default myRewrite;
// middlewareChains.ts
const MY_CHAIN: MiddlewareFactory[] = [myRewrite, withI18n];
export const myChain = stackMiddlewares(MY_CHAIN);

The 2nd one would be also achievable, like so:

const nextConfig = {
  async rewrites() {
    return [
      {
        destination: '/:lng/lp/sign-up',
        source: '/:lng/sign-up'
      }
    ];
  },

// * ...

As it would be very tedious to write all the redirections by hand, it would involve to codegen them.

gustaveWPM commented 7 months ago

Overkill + using a /pages/ segment doesn't solve the bundle size issue at all. Closing this as not planned.

gustaveWPM commented 7 months ago

Identified the real cause: https://github.com/Tirraa/dashboard_rtm/issues/86