npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

qs-props

v2.1.0

Published

This library makes it possible to handle query strings in Next.js getStaticProps.

Downloads

501

Readme

codecov npm version

: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

qs-props 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