Skip to content

Commit

Permalink
Next.js: ignore prefetch request for /logout middleware route
Browse files Browse the repository at this point in the history
  • Loading branch information
frankie567 committed Jun 5, 2023
1 parent 7e17298 commit 73b4629
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/nextjs/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ describe('middleware', () => {
},
]);

describe('logout', () => {
describe('login', () => {
it('should redirect to Fief authentication URL', async () => {
const request = new NextRequest('http://localhost:3000/login');
const response = await middleware(request);
Expand Down Expand Up @@ -156,6 +156,15 @@ describe('middleware', () => {
});

describe('logout', () => {
it('should do nothing and just return empty response on prefetch', async () => {
const request = new NextRequest('http://localhost:3000/logout', { headers: { 'X-Middleware-Prefetch': '1' } });
const response = await middleware(request);

expect(response.status).toBe(204);

expect(response.cookies.get('user_session')).toBeUndefined();
});

it('should clear session cookie and redirect to Fief logout URL', async () => {
const request = new NextRequest('http://localhost:3000/logout');
const response = await middleware(request);
Expand Down
11 changes: 11 additions & 0 deletions src/nextjs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,13 @@ class FiefAuth {
authenticate: this.fiefAuthEdge.authenticate(parameters),
}));
return async (request: NextRequest): Promise<NextResponse> => {
const isPrefetchRequest = request.headers.get('X-Middleware-Prefetch') === '1';

// Handle login
if (request.nextUrl.pathname === this.loginPath) {
if (isPrefetchRequest) {
return new NextResponse(null, { status: 204 });
}
const authURL = await this.client.getAuthURL({ redirectURI: this.redirectURI, scope: ['openid'] });
const response = NextResponse.redirect(authURL);
const returnTo = request.nextUrl.searchParams.get('return_to');
Expand All @@ -327,6 +332,9 @@ class FiefAuth {

// Handle authentication callback
if (request.nextUrl.pathname === this.redirectPath) {
if (isPrefetchRequest) {
return new NextResponse(null, { status: 204 });
}
const code = request.nextUrl.searchParams.get('code');
const [tokens] = await this.client.authCallback(code as string, this.redirectURI);

Expand All @@ -349,6 +357,9 @@ class FiefAuth {

// Handle logout
if (request.nextUrl.pathname === this.logoutPath) {
if (isPrefetchRequest) {
return new NextResponse(null, { status: 204 });
}
const logoutURL = await this.client.getLogoutURL({ redirectURI: this.logoutRedirectURI });
const response = NextResponse.redirect(logoutURL);
response.cookies.set(this.sessionCookieName, '', { maxAge: 0 });
Expand Down

0 comments on commit 73b4629

Please sign in to comment.