Git Product home page Git Product logo

nextjs-lingui-rsc-poc's Introduction

This is working PoC of Lingui with React Server Components in NextJS

How it works

  1. "simulate" context feature in RSC with React.cache function. Having that, we can use <Trans> in any place in RSC tree without prop drilling.

    // /src/i18n/i18n.ts
    import { cache } from 'react';
    import type { I18n } from '@lingui/core';
    
    export function setI18n(i18n: I18n) {
      getLinguiCtx().current = i18n;
    }
    
    export function getI18n(): I18n | undefined {
      return getLinguiCtx().current;
    }
    
    const getLinguiCtx = cache((): {current: I18n | undefined} => {
      return {current: undefined};
    })

    Then we need to setup Lingui for RSC in page component:

    // /src/app/[locale]/page.tsx
    export default async function Home({ params }) {
      const catalog = await loadCatalog(params.locale);
    
      const i18n = setupI18n({
        locale: params.locale,
        messages: { [params.locale]: catalog },
      });
    
      setI18n(
        i18n,
      );
    }

    And then in any RSC:

    const i18n = getI18n()
  2. Withing this being in place, we have to create a separate version of <Trans> which is using getI18n() instead of useContext().

    Lingui since version 4.4.1 exposing separate endpoint @lingui/react/server with a <TransNoContext> component which is not using Context feature. Our new component is a wrapper around <TransNoContext>.

    import React from "react"
    
    import { getI18n } from './i18n';
    import { TransNoContext, TransProps } from '@lingui/react/server';
    
    export function Trans(props: TransProps): React.ReactElement<any, any> | null {
      const i18n = getI18n()
    
      if (!i18n) {
        throw new Error('Lingui for RSC is not initialized. Use `setI18n()` first in root of your RSC tree.');
      }
    
      return <TransNoContext {...props} lingui={{ i18n }}/>
    }
  3. Having this is already enough, you can use RSC version in the server components and regular version in client. But that is not really great DX, we can automatically detect RSC components and swap implementation thanks to webpack magic. This is done by:

    • macro configured to insert import {Trans} from 'virtual-lingui-trans'
    • webpack has a custom resolve plugin which depending on the resolver context will resolve the virtual name to RSC or Regular version.
    const TRANS_VIRTUAL_MODULE_NAME = 'virtual-lingui-trans';
    
    class LinguiTransRscResolver {
      apply(resolver) {
        const target = resolver.ensureHook('resolve');
        resolver
          .getHook('resolve')
          .tapAsync('LinguiTransRscResolver', (request, resolveContext, callback) => {
    
            if (request.request === TRANS_VIRTUAL_MODULE_NAME) {
              const req = {
                ...request,
                // nextjs putting  `issuerLayer: 'rsc' | 'ssr'` into the context of resolver. 
                // We can use it for our purpose:
                request: request.context.issuerLayer === 'rsc'
                  // RSC Version without Context
                  ? path.resolve('./src/i18n/rsc-trans.tsx')
                  // Regular version
                  : '@lingui/react',
              };
    
              return resolver.doResolve(target, req, null, resolveContext, callback);
            }
    
            callback();
          });
      }
    }

Implementation consideration:

  • Webpack magic uses undocumented feature of NextJS (issuerLayer: 'rsc' | 'ssr'), that might break at any moment without semver bumping.
  • Detecting language and routing is up to user implementation. This repo uses segment based i18n by creating /src/app/[locale] folder. I think it's out of the Lingui scope.
  • We still need to configure separately Lingui for RSC and client components. It seems it's a restriction of RSC design which is not avoidable. So you have to use I18nProvider in every root with client components. (or do everything as RSC)

Any feedback or suggestions are welcome here lingui/js-lingui#1698

Getting Started

First, run the development server:

npm run dev
# or
yarn dev
# or
pnpm dev

Open http://localhost:3000/en/ with your browser to see the result.

You can start editing the page by modifying app/page.tsx. The page auto-updates as you edit the file.

Learn More

To learn more about Next.js, take a look at the following resources:

You can check out the Next.js GitHub repository - your feedback and contributions are welcome!

Deploy on Vercel

The easiest way to deploy your Next.js app is to use the Vercel Platform from the creators of Next.js.

Check out our Next.js deployment documentation for more details.

nextjs-lingui-rsc-poc's People

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.