Skip to content

Commit b3ffadd

Browse files
authored
fix(nextjs): Check if public dir exists (#3602)
When instrumenting the nextjs server, we should check if the public directory exists.
1 parent 6afe381 commit b3ffadd

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

packages/nextjs/src/utils/instrumentServer.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -161,23 +161,31 @@ function makeWrappedErrorLogger(origErrorLogger: ErrorLogger): WrappedErrorLogge
161161
};
162162
}
163163

164+
// inspired by next's public file routing; see
165+
// https://github.com/vercel/next.js/blob/4443d6f3d36b107e833376c2720c1e206eee720d/packages/next/next-server/server/next-server.ts#L1166
166+
function getPublicDirFiles(): Set<string> {
167+
try {
168+
// we need the paths here to match the format of a request url, which means they must:
169+
// - start with a slash
170+
// - use forward slashes rather than backslashes
171+
// - be URL-encoded
172+
const dirContents = deepReadDirSync(liveServer.publicDir).map(filepath =>
173+
encodeURI(`/${filepath.replace(/\\/g, '/')}`),
174+
);
175+
return new Set(dirContents);
176+
} catch (_) {
177+
return new Set();
178+
}
179+
}
180+
164181
/**
165182
* Wrap the server's request handler to be able to create request transactions.
166183
*
167184
* @param origReqHandler The original request handler from the `Server` class
168185
* @returns A wrapped version of that handler
169186
*/
170187
function makeWrappedReqHandler(origReqHandler: ReqHandler): WrappedReqHandler {
171-
// inspired by next's public file routing; see
172-
// https://github.com/vercel/next.js/blob/4443d6f3d36b107e833376c2720c1e206eee720d/packages/next/next-server/server/next-server.ts#L1166
173-
const publicDirFiles = new Set(
174-
// we need the paths here to match the format of a request url, which means they must:
175-
// - start with a slash
176-
// - use forward slashes rather than backslashes
177-
// - be URL-encoded
178-
deepReadDirSync(liveServer.publicDir).map(filepath => encodeURI(`/${filepath.replace(/\\/g, '/')}`)),
179-
);
180-
188+
const publicDirFiles = getPublicDirFiles();
181189
// add transaction start and stop to the normal request handling
182190
const wrappedReqHandler = async function(
183191
this: Server,

0 commit comments

Comments
 (0)