Koa-like middlewares for Next.js Server Side Rendering
SemVer | status | Next.js | MobX | MobX i18n |
---|---|---|---|---|
>=0.9 |
✅developing | >=15 |
>=6.11 |
>=0.5 |
>=0.7 <0.9 |
❌deprecated | >=9 <15 |
>=6.11 |
>=0.5 |
<0.7 |
❌deprecated | >=9 <15 |
>=4 <6.11 |
<0.5 |
pages/user/[id].tsx
import {
JWTProps,
RouterProps,
jwtVerifier,
cache,
errorLogger,
router,
translator
} from 'next-ssr-middleware';
import i18n from '../../model/Translation';
import { User, UserModel } from '../../model/User';
type UserDetailPageProps = User & JWTProps & RouterProps;
export const getServerSideProps = compose<{ id: string }, UserDetailPageProps>(
jwtVerifier(), // set `JWT_SECRET` in `.env.local` first
cache(),
errorLogger,
router,
translator(i18n),
async ({ params }) => {
const props = await new UserModel().getOne(params!.id);
return { notFound: !props, props };
}
);
export default function UserDetailPage({
jwtPayload,
route,
name,
summary
}: UserDetailPageProps) {
return (
<>
<h1>
{name} - {route.params!.id}
</h1>
<p>{summary}</p>
</>
);
}
middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { parseHeaders } from 'next-ssr-middleware';
export const config = {
// Matcher ignoring `/_next/`, `/api/` & icons
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|apple-icon|icon).*)'
]
};
export const middleware = ({ headers }: NextRequest) =>
NextResponse.next({ headers: parseHeaders(headers) });
app/page.tsx
import { compose, withMiddleware, ServerProps } from 'next-ssr-middleware';
const getServerSideProps = compose(async () => {
const props = await (
await fetch('https://api.github.com/orgs/idea2app')
).json();
return { props };
});
const HomePage = withMiddleware(getServerSideProps, Home);
export default HomePage;
async function Home({ params, searchParams, ...props }: ServerProps) {
return (
<>
<h1>Home</h1>
<pre>{JSON.stringify(props, null, 4)}</pre>
</>
);
}