r.mediaType === state.key) || renderers[0];
+ const hasMultipleMediaTypes = renderers.length >= 2;
+ const hasMultipleExamples = selected.examples.length >= 2;
+
+ // Only render the wrapper div if at least one selector will render
+ if (!hasMultipleMediaTypes && !hasMultipleExamples) {
+ return null;
+ }
+
return (
diff --git a/packages/react-openapi/src/code-samples.ts b/packages/react-openapi/src/code-samples.ts
index 7c357b4fb..f8be2d933 100644
--- a/packages/react-openapi/src/code-samples.ts
+++ b/packages/react-openapi/src/code-samples.ts
@@ -13,6 +13,7 @@ import {
} from './contentTypeChecks';
import { json2xml } from './json2xml';
import { stringifyOpenAPI } from './stringifyOpenAPI';
+import { isValidServerHost } from './util/server';
export interface CodeSampleInput {
method: string;
@@ -69,9 +70,12 @@ export const codeSampleGenerators: CodeSampleGenerator[] = [
const bodyString = body ? `\n${body}` : '';
+ // Only include Host header if origin is considered a valid server host
+ const hasValidHost = isValidServerHost(origin);
+ const hostLine = hasValidHost ? `Host: ${origin.replaceAll(/https?:\/\//g, '')}\n` : '';
+
const httpRequest = `${method.toUpperCase()} ${decodeURI(path)} HTTP/1.1
-Host: ${origin.replaceAll(/https*:\/\//g, '')}
-${headerString}${bodyString}`;
+${hostLine}${headerString}${bodyString}`;
return httpRequest;
},
diff --git a/packages/react-openapi/src/util/server.ts b/packages/react-openapi/src/util/server.ts
index f56970094..81379598f 100644
--- a/packages/react-openapi/src/util/server.ts
+++ b/packages/react-openapi/src/util/server.ts
@@ -45,3 +45,31 @@ function parseServerURL(url: string) {
}
return result;
}
+
+/**
+ * Check if any server has a host that can be used in an HTTP request.
+ * This is used to determine if the "Try it" button should be shown.
+ */
+export function hasValidServerHost(servers: OpenAPIV3.ServerObject[]): boolean {
+ if (servers.length === 0) {
+ return false;
+ }
+
+ return servers.some((server) => {
+ const url = interpolateServerURL(server);
+ return isValidServerHost(url);
+ });
+}
+
+/**
+ * Check if the server host/URL is valid for making direct HTTP requests.
+ * Accepts both full URLs (with protocol) and hostnames (without protocol).
+ */
+export function isValidServerHost(url: string): boolean {
+ // Check if URL starts with http:// or https://
+ if (url.startsWith('http://') || url.startsWith('https://')) {
+ return true;
+ }
+
+ return /^(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/.test(url);
+}