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
};
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
// contexts/auth.js
// append this new bit a the end:
export const ProtectRoute = ({ children }) => {
const { isAuthenticated, isLoading } = useAuth();
if (isLoading || (!isAuthenticated && window.location.pathname !== '/login')){
return <LoadingScreen />;
}
return children;
};
// _app.js
import React from 'react'
import { ProtectRoute } from '../contexts/auth'
function MyApp({ Component, pageProps }: AppProps) {
return (
<AuthProvider>
<ProtectRoute>
<Component {pageProps} />
</ProtectRoute>
</AuthProvider>
)
}
export default MyApp
xxxxxxxxxx
ALTER TABLE my_table ADD CONSTRAINT constraint_name PRIMARY KEY (col_1, col_2)