xxxxxxxxxx
import fs from "fs";
import fetch from "node-fetch";
import FileType from "file-type";
const API_URL_HERE = "your-api-url.whatever";
async function savePhotoFromAPI() {
const response = await fetch(API_URL_HERE);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
const fileType = await FileType.fromBuffer(buffer);
if (fileType.ext) {
const outputFileName = `yourfilenamehere.${fileType.ext}`
fs.createWriteStream(outputFileName).write(buffer);
} else {
console.log('File type could not be reliably determined! The binary data may be malformed! No file saved!')
}
}
savePhotoFromAPI();
xxxxxxxxxx
export async function getServerSideProps({ req, res }) {
const { Auth } = withSSRContext({ req })
try {
const user = await Auth.currentAuthenticatedUser()
return {
props: {
authenticated: true,
username: user.username
}
}
} catch (err) {
res.writeHead(302, { Location: '/profile' })
res.end()
}
return {props: {}}
}
export default Protected
xxxxxxxxxx
// middleware.js
import { NextResponse } from "next/server";
export function middleware(request) {
const token = request.cookies.get("token"); // Assuming the token is stored in cookies
const protectedRoutes = ["/my-account"]; // List of protected routes
const isProtected = protectedRoutes.some((route) =>
request.nextUrl.pathname.startsWith(route)
);
if (isProtected && !token) {
// If the user is not authenticated, redirect to the login page
const loginUrl = new URL("/login", request.url);
return NextResponse.redirect(loginUrl);
}
// Allow request to continue if authenticated or route is not protected
return NextResponse.next();
}
// Specify the matcher for routes you want the middleware to run on
export const config = {
matcher: ["/my-account/:path*"], // Apply middleware to these routes
};