How I can integrate Django with NextJS efficiently? Can you share it, please? If you have any public projects! Or the way to get it done!
How I can integrate Django with NextJS efficiently? Can you share it, please? If you have any public projects! Or the way to get it done!
I do not have experience with NextJS but I think what u are searching for is CORS. The Django Cors Headers package will do the job and has perfect documentation on how to set this up. Your NextJS app can then get the appropriate data from your Django Back-end API using something like Axios.
Happy coding!
I have built an admin console with modern React but backed by Django.
Next.js for admin pagesDjango for backend, login into dashboard, user management. Admins page are implemented by embed Next.js pages via Django templatesDjango views too!Steps:
% include % (Django Template Syntax)assetPrefix in next.config.js to prevent static files conflict between Next.js and DjangoTrying to show the naive exapmle:
// Next.js project
// /pages/post/index.js
...
useEffect(() => {
fetchPosts(...).then(data
});
// /pages/post/[id].js
...
const router = useRouter();
const { id } = router.query;
useEffect(() => {
fetchPost(id).then()...
});
// npm run export
out/_next
out/post.html
out/post/[id].html
// use gulp.js or sth to copy the exported files (`out`) into Django project (`static` and `templates` folder)
django-app/static/_next // I copy _next into static and make Django serve its statics + Next.js _next
// These two pages above from out
django-app/templates/next-admin/post.html
django-app/templates/next-admin/post/[id].html
// Django project
// templates
// django-app/templates/post/list.html
{% block content %}
{% include "next-admin/post.html" %}
{% endblock %}
// django-app/templates/post/detail.html
{% block content %}
{% include "next-admin/post/[id].html" %}
{% endblock %}
// views.py
def post_list_view(request):
return render(request, 'post/list.html', {})
def post_detail_view(request, _id):
return render(request, 'post/detail.html', {"id": _id})
// urls.py
path('post', post_list_ivew, name='post-list'),
path('post/<str:_id>', post_detail_view, name='post-detail'),
// Next.js npm run export -> Django python manage.py runserver
// Maybe you have to install corsheader for client data fetching
// And custom the admin/base.html or base_site.html for adding navigation links to your admin pages built by Next.js
Conclusion: