Skip to content

Commit 3486fff

Browse files
committed
modified middleware
1 parent 43dcb2c commit 3486fff

File tree

7 files changed

+132
-58
lines changed

7 files changed

+132
-58
lines changed

dataBuild.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"testData":[{"buildTime":5482},{"buildTime":16941},{"buildTime":9207},{"buildTime":5564},{"buildTime":5936},{"buildTime":6563},{"buildTime":10520,"apiKey":"1234567890"},{"buildTime":"201","apiKey":"aowifhojbefkw"},{"buildTime":"201","apiKey":"aowifhojbefkw"},{"buildTime":"201","apiKey":"aowifhojbefkw"}]}
1+
{"testData":[{"buildTime":5482},{"buildTime":16941},{"buildTime":9207},{"buildTime":5564},{"buildTime":5936},{"buildTime":6563},{"buildTime":10520,"apiKey":"1234567890"},{"buildTime":"201","apiKey":"aowifhojbefkw"},{"buildTime":"201","apiKey":"aowifhojbefkw"},{"buildTime":"201","apiKey":"aowifhojbefkw"},{"buildTime":"202","apiKey":"plsworkk!!!!"},{"buildTime":"202","apiKey":"plsworkk!!!!"},{"buildTime":"24230","apiKey":"plsworkk!!!!"},{"buildTime":5500,"apiKey":"1234567890"},{"buildTime":"24230","apiKey":"plsworkk!!!!"}]}

dataBundle.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
{"testData":[{"bundleLog":" ▲ Next.js 14.2.4\n - Environments: .env.local\n\n Creating an optimized production build ...\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/nodejs.html\n\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/edge.html\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/client.html\n ✓ Compiled successfully\n Linting and checking validity of types ...\n Collecting page data ...\n Generating static pages (0/5) ...\n Generating static pages (1/5) \r\n Generating static pages (2/5) \r\n Generating static pages (3/5) \r\n ✓ Generating static pages (5/5)\n Finalizing page optimization ...\n Collecting build traces ...\n\nRoute (app) Size First Load JS\n┌ ○ / 5.42 kB 92.4 kB\n└ ○ /_not-found 871 B 87.9 kB\n+ First Load JS shared by all 87 kB\n ├ chunks/23-ef3c75ca91144cad.js 31.5 kB\n ├ chunks/fd9d1056-2821b0f0cabcd8bd.js 53.6 kB\n └ other shared chunks (total) 1.87 kB\n\n\n○ (Static) prerendered as static content\n\n"},{"bundleLog":" ▲ Next.js 14.2.4\n - Environments: .env.local\n\n Creating an optimized production build ...\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/nodejs.html\n\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/edge.html\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/client.html\n ✓ Compiled successfully\n Linting and checking validity of types ...\n Collecting page data ...\n Generating static pages (0/5) ...\n Generating static pages (1/5) \r\n Generating static pages (2/5) \r\n Generating static pages (3/5) \r\n ✓ Generating static pages (5/5)\n Finalizing page optimization ...\n Collecting build traces ...\n\nRoute (app) Size First Load JS\n┌ ○ / 5.42 kB 92.5 kB\n└ ○ /_not-found 871 B 87.9 kB\n+ First Load JS shared by all 87.1 kB\n ├ chunks/23-ef3c75ca91144cad.js 31.5 kB\n ├ chunks/fd9d1056-2821b0f0cabcd8bd.js 53.6 kB\n └ other shared chunks (total) 1.9 kB\n\n\n○ (Static) prerendered as static content\n\n"}]}
1+
{"testData":[{"bundleLog":" ▲ Next.js 14.2.4\n - Environments: .env.local\n\n Creating an optimized production build ...\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/nodejs.html\n\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/edge.html\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/client.html\n ✓ Compiled successfully\n Linting and checking validity of types ...\n Collecting page data ...\n Generating static pages (0/5) ...\n Generating static pages (1/5) \r\n Generating static pages (2/5) \r\n Generating static pages (3/5) \r\n ✓ Generating static pages (5/5)\n Finalizing page optimization ...\n Collecting build traces ...\n\nRoute (app) Size First Load JS\n┌ ○ / 5.42 kB 92.4 kB\n└ ○ /_not-found 871 B 87.9 kB\n+ First Load JS shared by all 87 kB\n ├ chunks/23-ef3c75ca91144cad.js 31.5 kB\n ├ chunks/fd9d1056-2821b0f0cabcd8bd.js 53.6 kB\n └ other shared chunks (total) 1.87 kB\n\n\n○ (Static) prerendered as static content\n\n"},{"bundleLog":" ▲ Next.js 14.2.4\n - Environments: .env.local\n\n Creating an optimized production build ...\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/nodejs.html\n\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/edge.html\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/client.html\n ✓ Compiled successfully\n Linting and checking validity of types ...\n Collecting page data ...\n Generating static pages (0/5) ...\n Generating static pages (1/5) \r\n Generating static pages (2/5) \r\n Generating static pages (3/5) \r\n ✓ Generating static pages (5/5)\n Finalizing page optimization ...\n Collecting build traces ...\n\nRoute (app) Size First Load JS\n┌ ○ / 5.42 kB 92.5 kB\n└ ○ /_not-found 871 B 87.9 kB\n+ First Load JS shared by all 87.1 kB\n ├ chunks/23-ef3c75ca91144cad.js 31.5 kB\n ├ chunks/fd9d1056-2821b0f0cabcd8bd.js 53.6 kB\n └ other shared chunks (total) 1.9 kB\n\n\n○ (Static) prerendered as static content\n\n"},{"bundleLog":" ▲ Next.js 14.2.4\n - Environments: .env.local\n\n Creating an optimized production build ...\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/nodejs.html\n\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/edge.html\nWebpack Bundle Analyzer saved report to /Users/nellysegimoto/Codesmith/dummyNextApp/.next/analyze/client.html\n ✓ Compiled successfully\n Linting and checking validity of types ...\n Collecting page data ...\n Generating static pages (0/5) ...\n Generating static pages (1/5) \r\n Generating static pages (2/5) \r\n Generating static pages (3/5) \r\n ✓ Generating static pages (5/5)\n Finalizing page optimization ...\n Collecting build traces ...\n\nRoute (app) Size First Load JS\n┌ ○ / 5.42 kB 92.5 kB\n└ ○ /_not-found 871 B 87.9 kB\n+ First Load JS shared by all 87.1 kB\n ├ chunks/23-ef3c75ca91144cad.js 31.5 kB\n ├ chunks/fd9d1056-2821b0f0cabcd8bd.js 53.6 kB\n └ other shared chunks (total) 1.9 kB\n\n\n○ (Static) prerendered as static content\n\n"}]}

next.config.mjs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,19 @@
11
/** @type {import('next').NextConfig} */
2-
const nextConfig = {};
2+
const nextConfig = {
3+
async headers() {
4+
return [
5+
{
6+
// Apply these headers to all routes in your application.
7+
source: '/:path*',
8+
headers: [
9+
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
10+
{ key: 'Access-Control-Allow-Origin', value: '*' }, // Replace '*' with your specific origin if needed
11+
{ key: 'Access-Control-Allow-Methods', value: 'GET,DELETE,PATCH,POST,PUT,OPTIONS' },
12+
{ key: 'Access-Control-Allow-Headers', value: 'Authorization, Content-Type' },
13+
],
14+
},
15+
];
16+
},
17+
};
318

419
export default nextConfig;

nextlevelpackage/cli.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ const { sendToApi } = require('./sendToApi');
55
const { spawn } = require('child_process');
66

77
const bundleBuildAnalyzer = () => {
8+
// const buildURL = `http://localhost:3000/dashboard/api/build`;
9+
// const bundleURL = `http://localhost:3000/dashboard/api/bundle`;
810
const buildURL = `https://www.nextlevel-dash.com/dashboard/api/build`;
911
const bundleURL = `https://www.nextlevel-dash.com/dashboard/api/bundle`;
1012

nextlevelpackage/sendToApi.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const sendToApi = (data, url) => {
2020
body,
2121
headers: {
2222
'Content-Type': 'application/json',
23-
'api-key': apiKey
23+
'Authorization': apiKey
2424
},
2525
keepalive: true
2626
}).catch(err => {

src/app/dashboard/api/build/route.js

Lines changed: 86 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,96 @@
11
import fs from 'fs/promises';
22
import path from 'path';
33
import { NextResponse } from 'next/server';
4-
import { corsMiddleware } from '../middleware';
5-
const testDataPath = path.join(process.cwd(), 'dataBuild.json');
64

5+
const testDataPath = path.join(process.cwd(), 'dataBuild.json');
76

8-
export async function GET(request) {
9-
try {
10-
const corsResponse = await corsMiddleware(request);
11-
console.log('get request made to /dashboard/api/build');
12-
const data = JSON.parse(await fs.readFile(testDataPath, 'utf8'));
13-
console.log('build time data:', data);
14-
//original version
15-
// return NextResponse.json(data, { headers: corsResponse.headers }); //does this need the new keyword?
16-
//new version - Combine CORS headers with JSON response
17-
const response = NextResponse.json(data);
18-
corsResponse.headers.forEach((value, key) => {
19-
response.headers.set(key, value);
20-
});
21-
return response;
22-
} catch (error) {
23-
console.error(error);
24-
return new NextResponse(`Internal Server Error: ${error.message}`, { status: 500 }); //does this need the new keyword?
25-
}
7+
export async function GET() {
8+
try {
9+
const data = JSON.parse(await fs.readFile(testDataPath, 'utf8'));
10+
return NextResponse.json(data);
11+
} catch (error) {
12+
console.error(error);
13+
return NextResponse.json({ error: error.message }, { status: 500 });
14+
}
2615
}
2716

2817
export async function POST(request) {
29-
try {
30-
const corsResponse = await corsMiddleware(request); // Apply CORS middleware
31-
console.log('post request made to /dashboard/api/build');
32-
const body = await request.json();
33-
const apiKey = request.headers.get('api-key');
34-
const newData = {
35-
"buildTime": body.buildTime, //do the keys need to be strings?
36-
"apiKey": apiKey,
37-
};
38-
const currentData = JSON.parse(await fs.readFile(testDataPath, 'utf8'));
39-
currentData.testData.push(newData);
40-
await fs.writeFile(testDataPath, JSON.stringify(currentData));
41-
42-
//original version
43-
// return NextResponse(JSON.stringify(newData), { //does this need the new keyword?
44-
// headers: corsResponse.headers,
45-
// status: 201,
46-
// });
47-
48-
//new version - Combine CORS headers with JSON response
49-
const response = new NextResponse(JSON.stringify(newData), { status: 201 });
50-
corsResponse.headers.forEach((value, key) => {
51-
response.headers.set(key, value);
52-
});
53-
return response;
54-
55-
} catch (error) {
56-
console.error(error);
57-
return new NextResponse('Internal Server Error', { status: 500 }); //does this need the new keyword?
58-
}
18+
try {
19+
const body = await request.json();
20+
const apiKey = request.headers.get('Authorization');
21+
const newData = {
22+
buildTime: body.buildTime,
23+
apiKey: apiKey,
24+
};
25+
const currentData = JSON.parse(await fs.readFile(testDataPath, 'utf8'));
26+
currentData.testData.push(newData);
27+
await fs.writeFile(testDataPath, JSON.stringify(currentData));
28+
29+
return NextResponse.json(newData, { status: 201 });
30+
} catch (error) {
31+
console.error(error);
32+
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
33+
}
5934
}
6035

36+
37+
// import fs from 'fs/promises';
38+
// import path from 'path';
39+
// import { NextResponse } from 'next/server';
40+
// import { corsMiddleware } from '../middleware';
41+
// const testDataPath = path.join(process.cwd(), 'dataBuild.json');
42+
43+
44+
// export async function GET(request) {
45+
// try {
46+
// const corsResponse = await corsMiddleware(request);
47+
// console.log('get request made to /dashboard/api/build');
48+
// const data = JSON.parse(await fs.readFile(testDataPath, 'utf8'));
49+
// console.log('build time data:', data);
50+
// //original version
51+
// // return NextResponse.json(data, { headers: corsResponse.headers }); //does this need the new keyword?
52+
// //new version - Combine CORS headers with JSON response
53+
// const response = NextResponse.json(data);
54+
// corsResponse.headers.forEach((value, key) => {
55+
// response.headers.set(key, value);
56+
// });
57+
// return response;
58+
// } catch (error) {
59+
// console.error(error);
60+
// return new NextResponse(`Internal Server Error: ${error.message}`, { status: 500 }); //does this need the new keyword?
61+
// }
62+
// }
63+
64+
// export async function POST(request) {
65+
// try {
66+
// const corsResponse = await corsMiddleware(request); // Apply CORS middleware
67+
// console.log('post request made to /dashboard/api/build');
68+
// const body = await request.json();
69+
// const apiKey = request.headers.get('Authorization');
70+
// const newData = {
71+
// "buildTime": body.buildTime, //do the keys need to be strings?
72+
// "apiKey": apiKey,
73+
// };
74+
// const currentData = JSON.parse(await fs.readFile(testDataPath, 'utf8'));
75+
// currentData.testData.push(newData);
76+
// await fs.writeFile(testDataPath, JSON.stringify(currentData));
77+
78+
// //original version
79+
// // return NextResponse(JSON.stringify(newData), { //does this need the new keyword?
80+
// // headers: corsResponse.headers,
81+
// // status: 201,
82+
// // });
83+
84+
// //new version - Combine CORS headers with JSON response
85+
// const response = new NextResponse(JSON.stringify(newData), { status: 201 });
86+
// corsResponse.headers.forEach((value, key) => {
87+
// response.headers.set(key, value);
88+
// });
89+
// return response;
90+
91+
// } catch (error) {
92+
// console.error(error);
93+
// return new NextResponse('Internal Server Error', { status: 500 }); //does this need the new keyword?
94+
// }
95+
// }
96+

src/app/dashboard/api/middleware.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,31 @@
11
import { NextResponse } from 'next/server';
22

3-
export async function corsMiddleware(request) {
3+
export function middleware(request) {
44
const response = NextResponse.next();
55
response.headers.set('Access-Control-Allow-Credentials', 'true');
66
response.headers.set('Access-Control-Allow-Origin', '*'); // Replace '*' with your specific origin if needed
7-
response.headers.set('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT');
8-
response.headers.set('Access-Control-Allow-Headers', 'Connection, Postman-Token, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, api-key');
7+
response.headers.set('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT,OPTIONS');
8+
response.headers.set('Access-Control-Allow-Headers', 'Authorization, Content-Type');
9+
10+
// Handle OPTIONS method for CORS preflight request
11+
if (request.method === 'OPTIONS') {
12+
return response;
13+
}
14+
915
return response;
10-
}
16+
}
17+
18+
export const config = {
19+
matcher: '/dashboard/api/:path*',
20+
};
21+
22+
// import { NextResponse } from 'next/server';
23+
24+
// // export async function corsMiddleware(request) {
25+
// // const response = NextResponse.next();
26+
// // response.headers.set('Access-Control-Allow-Credentials', 'true');
27+
// // response.headers.set('Access-Control-Allow-Origin', '*'); // Replace '*' with your specific origin if needed
28+
// // response.headers.set('Access-Control-Allow-Methods', 'GET,DELETE,PATCH,POST,PUT');
29+
// // response.headers.set('Access-Control-Allow-Headers', 'Connection, Postman-Token, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, api-key');
30+
// // return response;
31+
// // }

0 commit comments

Comments
 (0)