Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use express res.locals with typescript inside next.js

I'm using express - next.js in my application and I'm passing some configuration to the client from the server through the res.locals, my project is in typescript and I using "@types/next": "^8.0.6".

the problem: typescript say "Property 'locals' does not exist on type 'ServerResponse | Partial<ServerResponse>'."

Expected answer: - a way to overwrite "NextContext.res" or "NextResponse" to be equal to Express.res instead of http.ServerResponse - A way to overwrite NextResponse to add locals: any | {x:strong}.

this is the simplify example of what we have and how to reproduce:

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';

type Props = {
  locals: {};
}

export default class MyDocument extends Document<Props> {
  render() {
    const { locals } = this.props;

    return (
      <html>
        <Head>
          <ComponentUsingLocalsInfo locals={locals} />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

MyDocument.getInitialProps = async (ctx) => {
  const { locals } = ctx.res;
  const initialProps = await Document.getInitialProps(ctx);

  return {
    ...initialProps,
    locals,
  }
}
like image 767
Nathan Redblur Avatar asked Nov 07 '22 15:11

Nathan Redblur


1 Answers

For a quick solution this is what worked for me:

    import { Response } from 'express';

    MyDocument.getInitialProps = async (ctx) => {

        const { locals } = (ctx.res as Response);

    }
like image 91
Colin Asadourian Avatar answered Nov 14 '22 18:11

Colin Asadourian