Create default admin user in Nextjs
Unanswered
Barbary Lion posted this in #help-forum
Barbary LionOP
I implemented Role based auth in my nextjs application and i want to create a default admin user when the app first runs and if no admin user exixts i tried doing it in multiple ways but no luck, any suggestions
10 Replies
What have you done? What did you try?
@Samuel Archibong What have you done? What did you try?
Barbary LionOP
export default withAuth(
function middleware(request: NextRequestWithAuth) {
if (
request.nextUrl.pathname.startsWith("/admin") &&
request.nextauth.token?.role !== "admin"
) {
return NextResponse.redirect(new URL("/denied", request.url));
} else if (
request.nextUrl.pathname.startsWith("/admin") &&
request.nextauth.token?.role === "admin"
) {
return NextResponse.next();
} else {
return NextResponse.redirect(new URL("/denied", request.url));
}
},
{
callbacks: {
authorized: ({ token }) => !!token,
},
}
);
export const config = {
matcher: "/admin/:path*",
}; export const authOptions = {
providers: [
CredentialsProvider({
name: "credentials",
credentials: {},
async authorize(credentials: any): Promise<any> {
const { email, password } = credentials;
try {
await connectToDB();
const user = await User.findOne({ email });
if (!user) {
return null;
}
const passwordsMatch = await bcrypt.compare(password, user.password);
if (!passwordsMatch) {
return null;
}
return user;
} catch (error) {
console.log("Error: ", error);
}
},
}),
],
session: {
strategy: "jwt",
},
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/",
},
callbacks: {
jwt({ token, user }: any) {
if (user) {
return { ...token, id: user.id, role: user.role }; // Add role property
}
return token;
},
session: ({ session, token }: any) => {
return {
...session,
user: {
...session.user,
id: token.id,
role: token.role,
},
};
},
},
}; i tried doing it with a server action it works but it will run every time the app is running which is not practicalI want to find out the best way to do this without messing up the app perf
I understand
I mean, reading your code, it's doing what you want it to do anyway
However to simple make it perorm well,
Here’s one approach using a server-side setup function. You can create a function to check if an admin user exists and create one if not, and call this function when the server starts.
Steps:
Create a setup function:
This function will check if an admin user exists in the database. If not, it will create one.
Call the setup function on server startup:
Depending on your setup, you might call this function in a custom server script or within a Next.js API route.
Here’s one approach using a server-side setup function. You can create a function to check if an admin user exists and create one if not, and call this function when the server starts.
Steps:
Create a setup function:
This function will check if an admin user exists in the database. If not, it will create one.
Call the setup function on server startup:
Depending on your setup, you might call this function in a custom server script or within a Next.js API route.
@Samuel Archibong However to simple make it perorm well,
Here’s one approach using a server-side setup function. You can create a function to check if an admin user exists and create one if not, and call this function when the server starts.
Steps:
Create a setup function:
This function will check if an admin user exists in the database. If not, it will create one.
Call the setup function on server startup:
Depending on your setup, you might call this function in a custom server script or within a Next.js API route.
Barbary LionOP
I was looking to do that but was not too sure if it was the right thing to do
@Samuel Archibong However to simple make it perorm well,
Here’s one approach using a server-side setup function. You can create a function to check if an admin user exists and create one if not, and call this function when the server starts.
Steps:
Create a setup function:
This function will check if an admin user exists in the database. If not, it will create one.
Call the setup function on server startup:
Depending on your setup, you might call this function in a custom server script or within a Next.js API route.
Barbary LionOP
Should i call this function in the middleware
@Barbary Lion Should i call this function in the middleware
As long as it solved the problem, sure
@Samuel Archibong As long as it solved the problem, sure
Barbary LionOP
Thanks