Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Chain responses in middleware. #1620

Merged
merged 10 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/sitecore-jss-nextjs/src/middleware/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export type MiddlewareBaseConfig = {

export abstract class MiddlewareBase {
protected SITE_SYMBOL = 'sc_site';
protected REWRITE_HEADER_NAME = 'x-sc-rewrite';
protected defaultHostname: string;

constructor(protected config: MiddlewareBaseConfig) {
Expand Down Expand Up @@ -100,4 +101,23 @@ export abstract class MiddlewareBase {

return this.config.siteResolver.getByHost(hostname);
}

/**
* Create a rewrite response
* @param {string} rewritePath the destionation path
* @param {NextRequest} req the current request
* @param {NextResponse} res the current response
*/
protected rewrite(rewritePath: string, req: NextRequest, res: NextResponse): NextResponse {
// Note an absolute URL is required: https://nextjs.org/docs/messages/middleware-relative-urls
const rewriteUrl = req.nextUrl.clone();
rewriteUrl.pathname = rewritePath;

const response = NextResponse.rewrite(rewriteUrl, res);

// Share rewrite path with following executed middlewares
response.headers.set(this.REWRITE_HEADER_NAME, rewritePath);

return response;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,10 @@ export class MultisiteMiddleware extends MiddlewareBase {
const rewritePath = getSiteRewrite(pathname, {
siteName,
});

// Note an absolute URL is required: https://nextjs.org/docs/messages/middleware-relative-urls
const rewriteUrl = req.nextUrl.clone();

rewriteUrl.pathname = rewritePath;

response = NextResponse.rewrite(rewriteUrl);
response = this.rewrite(rewritePath, req, response);

// Share site name with the following executed middlewares
response.cookies.set(this.SITE_SYMBOL, siteName);
// Share rewrite path with following executed middlewares
response.headers.set('x-sc-rewrite', rewritePath);

debug.multisite('multisite middleware end in %dms: %o', Date.now() - startTimestamp, {
rewritePath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,28 +243,11 @@ export class PersonalizeMiddleware extends MiddlewareBase {

// Rewrite to persononalized path
const rewritePath = getPersonalizedRewrite(basePath, { variantId });
// Note an absolute URL is required: https://nextjs.org/docs/messages/middleware-relative-urls
const rewriteUrl = req.nextUrl.clone();

// Preserve cookies from previous response
const cookies = response.cookies.getAll();

rewriteUrl.pathname = rewritePath;
response = NextResponse.rewrite(rewriteUrl, response);
response = this.rewrite(rewritePath, req, response);

// Disable preflight caching to force revalidation on client-side navigation (personalization may be influenced)
// See https://github.com/vercel/next.js/issues/32727
response.headers.set('x-middleware-cache', 'no-cache');
// Share rewrite path with following executed middleware
response.headers.set('x-sc-rewrite', rewritePath);
// Share site name with the following executed middlewares
response.cookies.set(this.SITE_SYMBOL, site.name);

// Restore cookies from previous response since
// browserId cookie gets omitted after rewrite
cookies.forEach((cookie) => {
response.cookies.set(cookie);
});

debug.personalize('personalize middleware end in %dms: %o', Date.now() - startTimestamp, {
rewritePath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,13 +352,16 @@ describe('RedirectsMiddleware', () => {
url: 'http://localhost:3000/found',
status: 301,
setCookies,
headers: new Headers({}),
});
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, status) => {
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, init) => {
const status = typeof init === 'number' ? init : init?.status || 307;
const headers = typeof init === 'object' ? init?.headers : {};
return ({
url,
status,
cookies: { set: setCookies },
headers: res.headers,
headers: new Headers(headers),
} as unknown) as NextResponse;
});
const req = createRequest({
Expand Down Expand Up @@ -411,7 +414,8 @@ describe('RedirectsMiddleware', () => {
status: 301,
setCookies,
});
const nextRewriteStub = sinon.stub(NextResponse, 'rewrite').callsFake((url) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const nextRewriteStub = sinon.stub(NextResponse, 'rewrite').callsFake((url, _init) => {
art-alexeyenko marked this conversation as resolved.
Show resolved Hide resolved
return ({
url,
status: 301,
Expand Down Expand Up @@ -526,7 +530,8 @@ describe('RedirectsMiddleware', () => {
status: 301,
setCookies,
});
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, status) => {
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, init) => {
const status = typeof init === 'number' ? init : init?.status || 307;
return ({
url,
status,
Expand Down Expand Up @@ -610,7 +615,6 @@ describe('RedirectsMiddleware', () => {

validateEndMessageDebugLog('redirects middleware end in %dms: %o', {
headers: {
'set-cookie': 'sc_site=nextjs-app; Path=/',
'x-middleware-next': '1',
},
redirected: false,
Expand Down Expand Up @@ -687,7 +691,8 @@ describe('RedirectsMiddleware', () => {
status: 302,
setCookies,
});
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, status) => {
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, init) => {
const status = typeof init === 'number' ? init : init?.status || 307;
return ({
url,
status,
Expand Down Expand Up @@ -746,7 +751,8 @@ describe('RedirectsMiddleware', () => {
status: 301,
setCookies,
});
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, status) => {
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, init) => {
const status = typeof init === 'number' ? init : init?.status || 307;
return ({
url,
status,
Expand Down Expand Up @@ -857,7 +863,8 @@ describe('RedirectsMiddleware', () => {
url: 'http://localhost:3000/found',
setCookies,
});
const nextRewriteStub = sinon.stub(NextResponse, 'rewrite').callsFake((url) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const nextRewriteStub = sinon.stub(NextResponse, 'rewrite').callsFake((url, _init) => {
art-alexeyenko marked this conversation as resolved.
Show resolved Hide resolved
return ({
url,
cookies: { set: setCookies },
Expand Down Expand Up @@ -908,7 +915,7 @@ describe('RedirectsMiddleware', () => {

it('should use sc_site cookie', async () => {
const siteName = 'foo';
const res = NextResponse.redirect('http://localhost:3000/found', 301);
const res = NextResponse.rewrite('http://localhost:3000/found');
res.cookies.set('sc_site', siteName);
const req = createRequest({
nextUrl: {
Expand All @@ -929,6 +936,11 @@ describe('RedirectsMiddleware', () => {
locale: 'en',
});

const expected = NextResponse.redirect('http://localhost:3000/found', {
status: 301,
headers: res.headers,
});

const finalRes = await middleware.getHandler()(req, res);

validateDebugLog('redirects middleware start: %o', {
Expand All @@ -941,6 +953,7 @@ describe('RedirectsMiddleware', () => {
headers: {
location: 'http://localhost:3000/found',
'set-cookie': 'sc_site=foo; Path=/',
'x-middleware-rewrite': 'http://localhost:3000/found',
},
redirected: false,
status: 301,
Expand All @@ -950,8 +963,8 @@ describe('RedirectsMiddleware', () => {
expect(siteResolver.getByHost).not.called.to.equal(true);
expect(siteResolver.getByName).to.be.calledWith(siteName);
expect(fetchRedirects).to.be.calledWith(siteName);
expect(finalRes).to.deep.equal(res);
expect(finalRes.status).to.equal(res.status);
expect(finalRes).to.deep.equal(expected);
expect(finalRes.status).to.equal(expected.status);
});

it('should preserve site name from response data when provided, if no redirect type defined', async () => {
Expand Down Expand Up @@ -1058,7 +1071,8 @@ describe('RedirectsMiddleware', () => {
status: 301,
setCookies,
});
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, status) => {
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, init) => {
const status = typeof init === 'number' ? init : init?.status || 307;
return ({
url,
status,
Expand Down Expand Up @@ -1119,7 +1133,8 @@ describe('RedirectsMiddleware', () => {
status: 301,
setCookies,
});
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, status) => {
const nextRedirectStub = sinon.stub(NextResponse, 'redirect').callsFake((url, init) => {
const status = typeof init === 'number' ? init : init?.status || 307;
return ({
url,
status,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class RedirectsMiddleware extends MiddlewareBase {
});

const createResponse = async () => {
if (this.config.disabled && this.config.disabled(req, NextResponse.next())) {
if (this.config.disabled && this.config.disabled(req, res || NextResponse.next())) {
debug.redirects('skipped (redirects middleware is disabled)');
return res || NextResponse.next();
}
Expand Down Expand Up @@ -129,22 +129,26 @@ export class RedirectsMiddleware extends MiddlewareBase {
/** return Response redirect with http code of redirect type **/
switch (existsRedirect.redirectType) {
case REDIRECT_TYPE_301:
return NextResponse.redirect(redirectUrl, 301);
return NextResponse.redirect(redirectUrl, {
art-alexeyenko marked this conversation as resolved.
Show resolved Hide resolved
status: 301,
statusText: 'Moved Permanently',
headers: res?.headers,
});
case REDIRECT_TYPE_302:
return NextResponse.redirect(redirectUrl, 302);
return NextResponse.redirect(redirectUrl, {
status: 302,
statusText: 'Found',
headers: res?.headers,
});
case REDIRECT_TYPE_SERVER_TRANSFER:
return NextResponse.rewrite(redirectUrl);
return NextResponse.rewrite(redirectUrl, res);
default:
return NextResponse.next();
return res || NextResponse.next();
}
};

const response = await createResponse();

// Share site name with the following executed middlewares
// Don't need to set when middleware is disabled
site && response.cookies.set(this.SITE_SYMBOL, site.name);

debug.redirects('redirects middleware end in %dms: %o', Date.now() - startTimestamp, {
redirected: response.redirected,
status: response.status,
Expand Down