tatethurston / nextjs-routes

Type safe routing for Next.js
MIT License
571 stars 23 forks source link

Server side redirect return #56

Closed saschb2b closed 2 years ago

saschb2b commented 2 years ago

We are using redirects for cases when data is not found or not present. Any way here to also type the source and destination parts for the redirect return?

For example

export const getServerSideProps: GetServerSideProps<DetailsPageProps> = async (context) => {
  const result = some fetching

  const data = result.data;

  if (!data) {
    return {
      redirect: {
        source: '/data/[id]',
        destination: '/',
        permanent: false,
      },
    };
  }

  return {
    props: {
      data,
    },
  };
};
tatethurston commented 2 years ago

Hey @saschb2b thanks for opening this. getServersideProps redirect does not perform the same interpolation as route so it can't support dynamic routes as typed by nextjs-routes.

We would need to add a runtime export to handle the route interpolation. This could look something like:

+ import { route } from 'nextjs-routes';

export const getServerSideProps: GetServerSideProps<DetailsPageProps> = async (context) => {
  const result = some fetching

  const data = result.data;

  if (!data) {
    return {
      redirect: {
        source: '/data/[id]',
-       destination: '/',
+.      // route accepts the same shape as `Link` from nextjs
+       destination: route({ pathname: '/' }),
        permanent: false,
      },
    };
  }

  return {
    props: {
      data,
    },
  };
};

This solution could also work for https://github.com/tatethurston/nextjs-routes/issues/36 and #38 . Let me know your thoughts.

Also question about your example above, where is source coming from? getServersideProps' redirect is typed as follows:

  statusCode: 301 | 302 | 303 | 307 | 308
  destination: string
  basePath?: false
saschb2b commented 2 years ago

That solution would be superb!

And yes you are right about source. I confused it with static redirects in the nextjs config https://nextjs.org/docs/api-reference/next.config.js/redirects and somehow used it without thinking about it too much. So it's only destination that needs to be typed

tatethurston commented 2 years ago

This is released in v0.0.21