Coder Social home page Coder Social logo

django-nextjs's People

Contributors

danialkeimasi avatar guoard avatar jvdboog avatar mjnaderi avatar robbiefernandez avatar seokeunju avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-nextjs's Issues

Having issues with NGINX

Not gonna lie, im pretty new to NGINX, even after reading the documentation and the production tab for nginx I still don't understand how to configure it well to work seamlessly with this package. I have it working well in development, just the process of moving it to production with nginx's configuration is where im having issues. Any Help or examples would be greatly appreciated

Request for compression support in django-nextjs

I have been using the django-nextjs library for my project and it has been a great help so far. However, I noticed that when I access the Next.js application directly on http://localhost:3000/ the JavaScript files are compressed with content-encoding gzip, but when I access the Django server (which is redirecting the files from Next.js), the files are no longer compressed.

I understand that the library does not currently support compression and I apologize if my request is an inconvenience. I have tried using the built-in GZipMiddleware in Django, but it did not work. I also tried using a reverse proxy like Nginx or Apache in front of my Django server, but it still doesn't work.

I would greatly appreciate it if compression support could be added to the django-nextjs library. This would make it easier for users like me to deliver compressed files to the client, improving performance and reducing bandwidth usage.

Thank you for your time and effort in maintaining this library, it has been a great help to me. Please let me know if you need any more information or if you have any questions.

Passing Data

how to passing data from django backend to next js pages?
i cant use {{ }} in next js pages

i am beginner in next js

Error Page Sync

Hi do you have a way to sync the 404 page in nextjs with the django backend error pages

views.py
from django_nextjs.render import render_nextjs_page_sync
def error_404(request, exception):
return render_nextjs_page_sync(request)

project/project/urls.py
handler404 = "apps.views.error_404"

_next/webpack-hmr' failed: / Too many redirects

Hello,

i've try to install the package like described in the readme.

Environment:

  • Next.js v12.2.4
  • Django 4.0.6

Everything was installed successfully but i have several errors:

First of all on index js i get the error: WebSocket connection to 'ws://127.0.0.1:8000/_next/webpack-hmr' failed:
Bildschirmfoto 2022-08-09 um 19 40 11

But i can see the nextjs index.

Then i want to try to change the route to /test

I described a view and parsed it to the url.
If i call the url i got the error: too many redirects and the page wouldn't load:

Bildschirmfoto 2022-08-09 um 19 43 54

Bildschirmfoto 2022-08-09 um 19 43 49

Here my Settings.py:

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'django-insecure-%2spqobsw&i$k(n(%(siwd#fxzh^h%wqk5nc3nx0_$upu8r5!q'

DEBUG = True

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "django_nextjs",
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'empire_next.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'empire_next.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


STATIC_URL = 'static/'



DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

views.py

from django.shortcuts import render

# Create your views here.

from django_nextjs.render import render_nextjs_page_sync


def index(request):
    return render_nextjs_page_sync(request)


def test(request):
    return render_nextjs_page_sync(request)

urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("backend.urls")),
    path("", include("django_nextjs.urls")),
]

backend.urly.py:

from django.urls import path
from .views import index
urlpatterns = [
    path("", index, name="index"),
    path("test/", index, name="test"),
]

any solution for this?

setup with django < 4.2

It seems this package has a dependency with django 4.2. Any pointers how I can use it with Django=="3.1.4"?

CookieError - Attempt to set a reserved key 'expires'

I am occasionally getting this error in my logs coming from _render_nextjs_page_to_string:

CookieError at {path}
Attempt to set a reserved key 'expires'

For some reason, bing's crawler/bot has a cookie name set with the name expires when it crawls my pages.

It seems that all cookies in the request are passed to _render_nextjs_page_to_string which then further processes it in aiohttp.ClientSession. Apparently it cannot handle cookies with reserved keywords. Perhaps we should sanitize the cookies by removing or ignoring the "expires" cookie name or any other cookie names with reserved keywords?

Full Traceback:

Traceback (most recent call last):
  File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/lib64/python3.8/concurrent/futures/_base.py", line 432, in result
    return self.__get_result()
  File "/usr/lib64/python3.8/concurrent/futures/_base.py", line 388, in __get_result
    raise self._exception
  File "/var/app/current/home/views.py", line 31, in nextjs_space_detail_slug
    return await render_nextjs_page(request)
  File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django_nextjs/render.py", line 148, in render_nextjs_page
    content, status, response_headers = await _render_nextjs_page_to_string(
  File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django_nextjs/render.py", line 99, in _render_nextjs_page_to_string
    async with aiohttp.ClientSession(
  File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/aiohttp/client.py", line 254, in __init__
    self._cookie_jar.update_cookies(cookies)
  File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/aiohttp/cookiejar.py", line 172, in update_cookies
    tmp[name] = cookie  # type: ignore[assignment]
  File "/usr/lib64/python3.8/http/cookies.py", line 495, in __setitem__
    self.__set(key, rval, cval)
  File "/usr/lib64/python3.8/http/cookies.py", line 485, in __set
    M.set(key, real_value, coded_value)
  File "/usr/lib64/python3.8/http/cookies.py", line 350, in set
    raise CookieError('Attempt to set a reserved key %r' % (key,))

ASGI Mode Causes Timeout Errors in Next.js Server-Side Rendering

Hello, I've encountered an issue when trying to integrate django-nextjs into my Django project. The issue arises when using ASGI and channels to run the server.

I have a URL path like so: url(r'^content', views.nextjs_content, name='content'), and the associated view function is an asynchronous function:

async def nextjs_content(request):
    return await render_nextjs_page(request)

Everything works perfectly fine in this setup, including Fast Refresh. However, when I introduce Server-Side Rendering (SSR) into my Next.js page (src/pages/content/[id].tsx), I start to encounter timeout errors. Specifically, my getServerSideProps function times out:

export async function getServerSideProps(context) {
    const { id } = context.params
    const url = `content/${id}/`

    try {
        const res = await axiosInstance.get(url)
        return { props: { data: res?.data } }
    } catch (error) {
        return {
            notFound: true,
        }
    }
}

The error I get is: AxiosError: timeout of 20000ms exceeded.

Interestingly, if I switch back to WSGI mode using python manage.py runserver --noasgi and add path("", include("django_nextjs.urls")) to my URLs, everything works fine. However, in this setup, I lose the benefit of Fast Refresh.

Could you provide some guidance on this? It seems like there might be some issue with the interaction between ASGI, Django-Nextjs, and Next.js's SSR.

Thank you for your time!

Issue when running nextjs

hey my nextjs version is:

@next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ @next/[email protected]
├─ [email protected]
│  ├─ @next/[email protected]
│  ├─ resolve@^2.0.0-next.3
│  ├─ [email protected]
├─ [email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]
│  ├─ @next/[email protected]

I am getting 'WebSocket connection to 'ws://localhost:8000/_next/webpack-hmr' failed: ' screenshot attached
Screenshot at May 26 22-07-27

for next.js v12 vercel.svg can not loaded

After changing to Django channels and asgi.py in order to make websocket work, I tried all static files deployment configuration for Django 4, nothing works for correct loading vercel.svg. Please provide some guidance about this.

for next.js v12 thru Django channels, 'admin/' doesn't work

after changing to channels with asgi.py, 'admin' listed in urls.py can not accessed correctly. any guidance about how to handle middleware like this? Thanks,

my urls.py is:

from django.contrib import admin
from django.urls import include, path, re_path
from django.views.generic.base import RedirectView
# from .views import jobs

# favicon_view = RedirectView.as_view(url='static/vercel.svg', permanent=True)

urlpatterns = [
    # path('', jobs),
    path('admin/', admin.site.urls),
    re_path(r'^vercel\.svg$', RedirectView.as_view(url='static/vercel.svg')),
    path('favicon.ico', RedirectView.as_view(url='static/favicon.ico')),  
]

all these 3 paths are not working if channels and django-nextjs enabled in INSTALLED_APPS in settings.py.

Is it possible for me to add the second frontend?

I need to integrate with two next.js frontend.

one is for regular user and other is for admin.

The two frontends are separated, and one is on 3000 and other is on 3001

I need to use 3001 when I redirect to /admin

How can I solve this problem?

Cannot visit another endpoint

I followed the steps from this tutorial. I added the created a new app called frontend and added the following codes:

# myproject/urls.py
from django.urls import include, path
urlpatterns = [
    # ...
    path("", include("frontend.urls")),
    path("", include("django_nextjs.urls")),
]
# frontend/views.py
from django_nextjs.render import render_nextjs_page_sync
def index(request):
    return render_nextjs_page_sync(request)
# frontend/urls.py
from django.urls import path
from .views import index
urlpatterns = [
    path("", index, name="index"),
]

I can now see the homepage (situated at "localhost:8000/" route) But I can't visit any other routes like "http://localhost:8000/create" which I can visit from my nextjs server "http://localhost:3000/create".

I tried adding a new route in frontend.urls.py like this

from django.urls import path
from .views import index

urlpatterns = [
    path("", index, name="index"),
    path("create/", index, name="index"),
]

but I kept getting too many redirects. Can someone show me the correct way to do this or is it even necessary to add endpoints manually?

Client-side navigation does not work with NextJS 13 + App router

When using NextJS 13 with the new app router, client-side navigation is not working and <Link> components cause the page to be reloaded, rather than replaced by JS. I've only tested this on the app router, so it's possible that the page router is also affected.

From what I can tell the issue is that requests made from the front-end use headers to tell the NextJS server if it should return full HTML or RSC. If the headers are not forwarded to NextJS, then the full HTML is always returned. NextJS also sets headers on the response that are required for this to work. These are the headers that I've found to be necessary:

Request/Response Header Name
Request Rsc
Request Next-Router-State-Tree
Request Next-Router-Prefetch
Request Next-Url
Request Cookie
Request Accept-Encoding
Response Vary
Response Content-Type

I discovered the request headers by looking at the Vary header for RSC requests.

I've got this working for me locally, so I'll open a PR with the changes I've made.

Issues when running the Django server in production mode

Hi,

If the Django server is set to run with debug=False, then all the requests will pass through the render_nextjs_page_sync, according to this statement in urls.py:

if settings.DEBUG:
    # only in dev environment
    urlpatterns.append(re_path(r"^(?:_next|__nextjs|next).*$", NextJSProxyView.as_view()))

The problem is that all the .js bundles requests will have their content-type property set to text/html, as this is happening for each request that passes through this view:

from django_nextjs.render import render_nextjs_page_sync

def index(request):
    return render_nextjs_page_sync(request)

Should the content-type be manually computed and then specified as an argument to the render_nextjs_page_sync method? I don't see other way around it.

Thank you!

Customizing the HTML Response: Fix hydration error with Nextjs 13+ app router

How to Reproduce

In Nextjs 13+, customize the root layout in app directory:

// app/layout.jsx (or .tsx)
...
<body id="__django_nextjs_body" className={inter.className}>
  <div id="__django_nextjs_body_begin" />
  {children}
  <div id="__django_nextjs_body_end" />
</body>
...

Write a django template that extends django_nextjs/document_base.html:

{% extends "django_nextjs/document_base.html" %}


{% block head %}
  <!-- ... the content you want to place at the beginning of "head" tag ... -->
  {{ block.super }}
  <!-- ... the content you want to place at the end of "head" tag ... -->
{% endblock %}


{% block body %}
  ... the content you want to place at the beginning of "body" tag ...
  ... e.g. include the navbar template ...
  {{ block.super }}
  ... the content you want to place at the end of "body" tag ...
  ... e.g. include the footer template ...
{% endblock %}

Pass the template name to render_nextjs_page:

async def jobs(request):
    return await render_nextjs_page(request, "path/to/template.html")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.