next-apollo-ssr v1.2.2
Next.js Apollo server-side rendering v1.2.2
Next.js is an awesome React.js framework that allows users to render information on the server - or in simpler words, perform server-side rendering. To learn more, click the links.
Why should I use this?
There are already many packages out there that help you render stuff on the server, but use something that is not recommended by the devs at Next.js - NextPage.getInitialProps
. This method prevents Next.js to provide you with the benefits of automatic static optimization, learn more in their docs.
Why this package is different
This package provides you with the options of server-side rendering using the new getServerSideProps
function, that makes it much easier to render on the server and even perform redirects.
Usage
utils/next-ssr.js
export const nextApolloService = new NextApolloService({
apolloClientConfig: {
cache: new InMemoryCache(), // You would always be using normalized caching
// .. options
},
graphqlCodegenModule: () => import("gql/__generated__"),
});
export const getUsers = nextApolloService.apolloFetch({
query: mod => mod.UsersDocument,
});
pages/_app.js
export default function App({ Component, pageProps }) {
const client = nextApolloService.useNextApollo(pageProps.initialApolloState);
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
);
}
pages/index.js
import gssp from "next-apollo-ssr/gssp";
import { getUsers } from "utils/next-ssr";
import { useUsersQuery } from "gql/__generated__";
export default function Home() {
const { data } = useUsersQuery();
// .. (use your server-side rendered data!)
}
// The `gssp` accepts and composes `GsspFetcher` types
export const getServerSideProps = gssp(getUsers);
Tip: This package is best used with TypeScript, but you will face absolutely no problems with JavaScript.
Creating a custom GsspFetcher
The following example shows how you can implement private routes in Next.js.
import { createGsspFetcher } from "next-apollo-ssr/gssp";
function auth(route) {
return createGsspFetcher(({ context, pageProps }, next) => {
const token = context.req.cookies.token;
// check for tokens, etc...
if (token) return next();
pageProps.redirect = {
destination: "/login",
permanent: false,
};
});
}
What to anticipate
- Support for
getStaticProps
andgetStaticPaths
Thanks
- YouTube - a pure Next.js expert (I have implemented his way of performing ssr)
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago