Koa-like middlewares for Next.js Back-end API & Server Side Rendering
SemVer | status | Next.js | MobX | MobX i18n |
---|---|---|---|---|
>=1.0 |
✅developing | >=15 |
>=6.11 |
❌ |
>=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 |
- Router
- Error logger
- JWT verifier
- Props cache
-
i18n loader(use MobX-i18n utility directly) - OAuth 2 signer (with common providers)
- GitHub
import {
JWTProps,
RouterProps,
jwtVerifier,
cache,
errorLogger,
router
} from 'next-ssr-middleware';
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,
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>
</>
);
}
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) });
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>
</>
);
}
Located in pages/api/
of a Next.js project or api/
of a Vercel serverless project.
import { createKoaRouter, withKoaRouter } from 'next-ssr-middleware';
export const config = { api: { bodyParser: false } };
const router = createKoaRouter(import.meta.url);
router
.get('/', async context => {
context.body = context.request.query;
})
.post('/', async context => {
context.status = 201;
context.body = Reflect.get(context.request, 'body');
});
export default withKoaRouter(router);
- https://github.com/idea2app/Next-Bootstrap-ts
- https://github.com/idea2app/Lark-Next-Bootstrap-ts
- https://github.com/FreeCodeCamp-Chengdu/FreeCodeCamp-Chengdu.github.io
- https://github.com/kaiyuanshe/kaiyuanshe.github.io
- https://github.com/kaiyuanshe/OpenHackathon-Web
- https://github.com/kaiyuanshe/OSS-toolbox