@@ -68,13 +68,31 @@ if (args.o) {
68
68
await open ( `http://localhost:3000${ adminRoute } ` )
69
69
}
70
70
71
+ const findOpenPort = ( startPort : number ) : Promise < number > => {
72
+ return new Promise ( ( resolve , reject ) => {
73
+ const server = createServer ( )
74
+ server . listen ( startPort , ( ) => {
75
+ console . log ( `✓ Running on port ${ startPort } ` )
76
+ server . close ( ( ) => resolve ( startPort ) )
77
+ } )
78
+ server . on ( 'error' , ( ) => {
79
+ console . log ( `⚠ Port ${ startPort } is in use, trying ${ startPort + 1 } instead.` )
80
+ findOpenPort ( startPort + 1 )
81
+ . then ( resolve )
82
+ . catch ( reject )
83
+ } )
84
+ } )
85
+ }
86
+
71
87
const port = process . env . PORT ? Number ( process . env . PORT ) : 3000
72
88
89
+ const availablePort = await findOpenPort ( port )
90
+
73
91
// @ts -expect-error the same as in test/helpers/initPayloadE2E.ts
74
92
const app = nextImport ( {
75
93
dev : true ,
76
94
hostname : 'localhost' ,
77
- port,
95
+ port : availablePort ,
78
96
dir : rootDir ,
79
97
} )
80
98
@@ -88,7 +106,7 @@ void app.prepare().then(() => {
88
106
createServer ( async ( req , res ) => {
89
107
const parsedUrl = parse ( req . url || '' , true )
90
108
await handle ( req , res , parsedUrl )
91
- } ) . listen ( port , ( ) => {
109
+ } ) . listen ( availablePort , ( ) => {
92
110
resolveServer ( )
93
111
} )
94
112
} )
@@ -97,8 +115,8 @@ await serverPromise
97
115
process . env . PAYLOAD_DROP_DATABASE = process . env . PAYLOAD_DROP_DATABASE === 'false' ? 'false' : 'true'
98
116
99
117
// fetch the admin url to force a render
100
- void fetch ( `http://localhost:${ port } ${ adminRoute } ` )
101
- void fetch ( `http://localhost:${ port } /api/access` )
118
+ void fetch ( `http://localhost:${ availablePort } ${ adminRoute } ` )
119
+ void fetch ( `http://localhost:${ availablePort } /api/access` )
102
120
// This ensures that the next-server process is killed when this process is killed and doesn't linger around.
103
121
process . on ( 'SIGINT' , ( ) => {
104
122
if ( child ) {
0 commit comments