Skip to content

Commit

Permalink
Merge pull request #10 from asyncink/pass-location-search
Browse files Browse the repository at this point in the history
feat: pass location.search to context on server
  • Loading branch information
andrepolischuk authored Nov 16, 2023
2 parents 34935f4 + 460408b commit ddca866
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export interface Context extends Record<string, any> {
req?: Request
/** Express [response](https://expressjs.com/en/4x/api.html#res) object (server-only) */
res?: Response
/** Location object (client-only, you can only use `location.pathname` on server) */
/** Location object (client-only, you can only use `location.pathname` and `location.search` on server) */
location?: Location
/** React Router navigate function (client-only) */
navigate?: NavigateFunction
Expand Down
5 changes: 4 additions & 1 deletion src/server/stream.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,15 @@ test('get page with assets', async () => {

test('get page with location object in context', async () => {
req.path = '/location'
req.originalUrl = '/location?foo=bar'
await renderToStream({req, res, routes})

expect(res.status).toBeCalledWith(200)
expect(res.data).toContain('<title>Location: /location</title>')
expect(res.data).toContain('<h1>Location</h1>')
expect(res.data).toContain(JSON.stringify({pathname: '/location'}))
expect(res.data).toContain(
JSON.stringify({pathname: '/location', search: '?foo=bar'})
)
})

test('get page with custom layout', async () => {
Expand Down
9 changes: 7 additions & 2 deletions src/server/stream.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,19 @@ export const renderToStream = async (
Document = BaseDocument,
...rest
} = options
const {path: pathname} = req
const {path: pathname, originalUrl} = req

const index = originalUrl?.indexOf('?')
const search = index >= 0 ? originalUrl.slice(index) : ''

const context = {
req,
res,
location: {
pathname
pathname,
search
} as Location,

...rest
}

Expand Down
3 changes: 2 additions & 1 deletion src/test/components/location.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ Location.getMetaData = async ({data}) => ({
})

Location.getInitialData = async ({location}) => ({
pathname: location.pathname
pathname: location.pathname,
search: location.search
})

export default Location

0 comments on commit ddca866

Please sign in to comment.