qs-props
v2.1.0
Published
This library makes it possible to handle query strings in Next.js getStaticProps.
Downloads
501
Readme
:bowl_with_spoon: qs-props
This library enhances getStaticProps
in Next.js.
Normally getStaticProps cannot include query strings in the static generation, only paths can be handled. This library uses middleware to convert query strings to paths so that getStaticProps can handle query strings.
This is useful when transferring a running web service to Next.js, and the URL format needs to be maintained for SEO.
Example
Require
- Using Next.js >=12
This plugin depends on the middleware of Next.js v12.
Installation
npm install --save qs-props
Usage
// middleware.ts
import { makeMiddleware } from 'qs-props'
export const middleware = makeMiddleware({
keys: ['size']
})
The file name of the page must be in the three dots format (...) such as [...queries].tsx
to handle multiple routes.
// /pages/[...queries].tsx
import { GetStaticPaths, GetStaticProps } from 'next'
import { qs } from 'qs-props'
const { getQueryStringProps, makeQuery } = qs(
['size'] as const,
'queries'
)
export const getStaticPaths: GetStaticPaths = () => {
return {
paths: ['large', 'medium', 'small'].map((size) => ({
params: makeQuery({ size })
})),
fallback: false
}
}
export const getStaticProps: GetStaticProps = (ctx) => {
const props = getQueryStringProps(ctx)
return { props }
}
const Page = (props) => {
return <div>{JSON.stringify(props)}</div>
}
makeMiddleware
Run it in the middleware file (middleware.ts).
Specify the list of keys to process as keys
. Unspecified keys will be ignored.
import { makeMiddleware } from 'qs-props'
export const middleware = makeMiddleware({
// Other than size and color, all other query strings will be ignored.
keys: ['color', 'size']
})
qs
You can use qs
to get two functions, getQueryStringProps
and makeQuery
.
The first argument should be the same value as keys
in makeMiddleware
. If you are using Typescript, you can get the benefit of type completion by making it readonly with as const
.
The second argument should be the same value as the page file name (path parameter name). For example, if the page file is pages/base/[...queries].tsx
, it is queries
.
const { getQueryStringProps, makeQuery } = qs(
['color', 'size'] as const,
'queries'
)
getQueryStringProps
getQueryStringProps
is a function that allows you to get the value of a query string from GetStaticPropsContext
.
// pages/base/[...queries].tsx
import { qs } from 'qs-props'
const { getQueryStringProps } = qs(
['color', 'size'] as const,
'queries'
)
export const getStaticProps: GetStaticProps = (ctx) => {
// props: { size: string; color: string }
const props = getQueryStringProps(ctx)
return { props }
}
To infer the type of the value obtained from getQueryStringProps
, set the first argument of qs
to be a readonly value.
makeQuery
makeQuery
is used to generate URLs for getStaticPaths
, router.push
router.replace
, and Link
component.
import { qs } from 'qs-props'
const { makeQuery } = qs(
['color', 'size'] as const,
'queries'
)
const Links = () => {
return (
<>
{['red', 'black', 'white'].map((color) => (
<Link
key={color}
href={{
pathname: '/base/[...queries]',
query: makeQuery({ color })
}}
as={`/base?color=${color}`}
>
{color}
</Link>
))}
</>
)
}
Be sure to use as
to make sure that the generated URLs come with a query string; without as
, the path generated by the sample code above will be /base/color-red
.
Note
About optional catch all routes
The page file can be in the format [[...queries]].tsx
(Optional catch all routes). However, in that case, you will not be able to navigate with Link components or prefetching functions such as router.push
and router.replace
.
Therefore, it is recommended to have two pages: index.tsx
to handle paths without query strings, and [...queries].tsx
for handling query strings.
Contributing
Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.
License
This project is licensed under the MIT License - see the LICENSE file for details